repo
string
commit
string
message
string
diff
string
tinku99/ahkdll
761f25b202fc760f92ada36e32bd85da584ab556
Revert default SendMode to SendEvent
diff --git a/source/defines.h b/source/defines.h index b33dcc3..aa7f792 100644 --- a/source/defines.h +++ b/source/defines.h @@ -272,602 +272,602 @@ struct ExprTokenType // Something in the compiler hates the name TokenType, so LPTSTR buf; size_t marker_length; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; }; }; // Note that marker's str-length should not be stored in this struct, even though it might be readily // available in places and thus help performance. This is because if it were stored and the marker // or SYM_VAR's var pointed to a location that was changed as a side effect of an expression's // call to a script function, the length would then be invalid. SymbolType symbol; // Short-circuit benchmark is currently much faster with this and the next beneath the union, perhaps due to CPU optimizations for 8-byte alignment. union { ExprTokenType *circuit_token; // Facilitates short-circuit boolean evaluation. LPTSTR mem_to_free; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; // The above two probably need to be adjacent to each other to conserve memory due to 8-byte alignment, // which is the default alignment (for performance reasons) in any struct that contains 8-byte members // such as double and __int64. }; #define MAX_TOKENS 512 // Max number of operators/operands. Seems enough to handle anything realistic, while conserving call-stack space. #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. // 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_ASSIGN, ACT_ASSIGNEXPR, ACT_EXPRESSION, ACT_ADD, ACT_SUB, ACT_MULT, ACT_DIV , ACT_ASSIGN_FIRST = ACT_ASSIGN, ACT_ASSIGN_LAST = ACT_DIV , ACT_ELSE // Parsed at a lower level than most commands to support same-line ELSE-actions (e.g. "else if"). , ACT_IFIN, ACT_IFNOTIN, ACT_IFCONTAINS, ACT_IFNOTCONTAINS, ACT_IFIS, ACT_IFISNOT , ACT_IFBETWEEN, ACT_IFNOTBETWEEN , ACT_IFEXPR // i.e. if (expr) // *** *** *** KEEP ALL OLD-STYLE/AUTOIT V2 IFs AFTER THIS (v1.0.20 bug fix). *** *** *** , ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // ACT_IS_IF_OLD() relies upon ACT_IFEQUAL through ACT_IFLESSOREQUAL being adjacent to one another // and it relies upon the fact that ACT_IFEQUAL is first in the series and ACT_IFLESSOREQUAL last. , ACT_IFEQUAL = ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION, ACT_IFNOTEQUAL, ACT_IFGREATER, ACT_IFGREATEROREQUAL , ACT_IFLESS, ACT_IFLESSOREQUAL , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes. , ACT_IFWINEXIST = ACT_FIRST_COMMAND , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE , ACT_IFINSTRING, ACT_IFNOTINSTRING , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX // Keep this range updated with any new IFs that are added. , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE , ACT_GETKEYSTATE , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS , ACT_STATUSBARGETTEXT , ACT_STATUSBARWAIT , ACT_CLIPWAIT, ACT_KEYWAIT , ACT_SLEEP, ACT_RANDOM , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_BREAKIF, ACT_CONTINUE, ACT_CONTINUEIF // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_TRY, ACT_CATCH, ACT_THROW, ACT_FINALLY , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE , ACT_WINHIDE, ACT_WINSHOW , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE // Keep rarely used actions near the bottom for parsing/performance reasons: , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME , ACT_FILEGETSIZE, ACT_FILEGETVERSION , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_SETREGVIEW , ACT_OUTPUTDEBUG , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME , ACT_SUSPEND, ACT_PAUSE , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET , ACT_EXITAPP , ACT_SHUTDOWN , ACT_FILEENCODING // Make these the last ones before the count so they will be less often processed. This helps // performance because this one doesn't actually have a keyword so will never result // in a match anyway. UPDATE: No longer used because Run/RunWait is now required, which greatly // improves syntax checking during load: //, ACT_EXEC // It's safer to use g_ActionCount, which is calculated immediately after the array is declared // and initialized, at which time we know its true size. However, the following lets us detect // when the size of the array doesn't match the enum (in debug mode): #ifdef _DEBUG , ACT_COUNT #endif }; enum enum_act_old { OLD_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order: , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS }; // It seems best not to include ACT_SUSPEND in the below, since the user may have marked // a large number of subroutines as "Suspend, Permit". Even PAUSE is iffy, since the user // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey // was 1 (the default). #ifndef MINIDLL #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \ || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS) #else #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_RELOAD) #endif #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance. #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF) #define ACT_IS_IF_OR_ELSE_OR_LOOP(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ActionType == ACT_LOOP || ActionType == ACT_WHILE || ActionType == ACT_FOR) #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \ && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL)) // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new") // can support parameters on the same line or on the next line. For example, both of the above are allowed: // IfMsgBox, No, Gosub, XXX // IfMsgBox, No // Gosub, XXX // 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 // 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. #ifndef MINIDLL #define MAX_INPUTBOXES 4 #define MAX_PROGRESS_WINDOWS 10 // Allow a lot for downloads and such. #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above. #define MAX_SPLASHIMAGE_WINDOWS 10 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above. #endif #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. #ifndef MINIDLL #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #endif #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. #ifndef MINIDLL #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #endif #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. #ifndef MINIDLL // 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 #endif #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 CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close() #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) && g_MainThreadID == aThreadID)\ 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; // Just make them int's, rather than something smaller, because the collection // of actions will take up very little memory. Int's are probably faster // for the processor to access since they are the native word size, or something: // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform() // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for // non-AutoIt2 scripts, such as the extra ones in StringGetPos). // Also, changing these from ints to chars greatly reduces 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, MaxParamsAu2WithHighBit; // Array indicating which args must be purely numeric. The first arg is // number 1, the second 2, etc (i.e. it doesn't start at zero). The list // is ended with a zero, much like a string. The compiler will notify us // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased: #define MAX_NUMERIC_PARAMS 7 ActionTypeType NumericParams[MAX_NUMERIC_PARAMS]; }; #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}; #ifndef MINIDLL 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("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")} enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely). , GUI_EVENT_RCLK, GUI_EVENT_COLCLK , GUI_EVENT_FIRST_UNNAMED // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below. , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield). #endif typedef USHORT CoordModeType; // Bit-field offsets: #ifndef MINIDLL #define COORD_MODE_PIXEL 0 #endif #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #ifndef MINIDLL #define COORD_MODE_MENU 8 #endif #define COORD_MODE_WINDOW 0 #define COORD_MODE_CLIENT 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #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; } // Same reason as above struct. It's best to keep this struct as small as possible // because it's used as a local (stack) var by at least one recursive function: // Each instance of this struct generally corresponds to a quasi-thread. The function that creates // a new thread typically saves the old thread's struct values on its stack so that they can later // be copied back into the g struct when the thread is resumed: class Func; // Forward declarations struct FuncAndToken { ExprTokenType mToken ; LPTSTR result_to_return_dll; Func * mFunc ; VARIANT variant_to_return_dll; ExprTokenType **param; ExprTokenType params[10]; LPTSTR buf; BYTE mParamCount; }; class Label; // class Line; // struct RegItemStruct; // struct LoopReadFileStruct; // #ifndef MINIDLL class GuiType; // #endif struct global_struct { // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious). __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values. __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. WIN32_FIND_DATA *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. // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class // because they're more appropriate as thread-attributes rather than being global to the entire script. TitleMatchModes TitleMatchMode; int IntervalBeforeRest; int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible. int Priority; // This thread's priority relative to others. DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. #ifndef MINIDLL GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click. #endif EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard. #ifndef MINIDLL POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed. GuiType *GuiWindow; // The GUI window that launched this thread. GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..." GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid. GuiType *DialogOwner; // This thread's GUI owner, if any. GuiIndexType GuiControlIndex; // The GUI control index that launched this thread. #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL) #endif 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; // TCHAR FormatFloat[32]; Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine. Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. //HWND hWndToRestore; int MsgBoxResult; // Which button was pressed in the most recent MsgBox. HWND DialogHWND; DWORD RegView; // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: SendModes SendMode; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. DWORD ThreadStartTime; int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too). bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness. 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 AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. 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; CoordModeType CoordMode; // Bitwise collection of flags. UCHAR StringCaseSense; // On/Off/Locale bool StoreCapslockMode; bool AutoTrim; char FormatInt; SendLevelType SendLevel; bool MsgBoxTimedOut; // Doesn't require initialization. bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle". bool ListLinesIsEnabled; UINT Encoding; ExprTokenType* ThrownToken; Line* ExcptLine; bool InTryBlock; }; inline void global_maximize_interruptibility(global_struct &g) { g.AllowThreadToBeInterrupted = true; g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.ThreadIsCritical = false; g.AllowTimers = true; #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. } inline void global_clear_state(global_struct &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 ErrorLevel shouldn't). { g.CurrentFunc = NULL; g.CurrentFuncGosub = NULL; g.CurrentLabel = NULL; g.hWndLastUsed = NULL; //g.hWndToRestore = NULL; g.MsgBoxResult = 0; g.IsPaused = false; g.UninterruptedLineCount = 0; #ifndef MINIDLL g.DialogOwner = NULL; #endif g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true. #ifndef MINIDLL g.GuiDefaultWindow = NULL; #endif // Above line is done because allowing it to be permanently changed by the auto-exec section // seems like it would cause more confusion that it's worth. A change to the global default // or even an override/always-use-this-window-number mode can be added if there is ever a // demand for it. 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.InTryBlock = false; } inline void global_init(global_struct &g) // This isn't made a real constructor to avoid the overhead, since there are times when we // want to declare a local var of type global_struct without having it initialized. { // 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: global_clear_state(g); - g.SendMode = SM_INPUT; + g.SendMode = SM_EVENT; // v1.0.43: Default to SM_EVENT for backward compatibility g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3. 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. // Not sure what the optimal default is. 1 seems too low (scripts would be very slow by default): g.LinesPerCycle = -1; g.IntervalBeforeRest = 10; // sleep for 10ms every 10ms #define DEFAULT_PEEK_FREQUENCY 5 g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL. g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values. g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.AllowTimers = true; g.ThreadIsCritical = false; g.Priority = 0; g.LastError = 0; #ifndef MINIDLL g.GuiEvent = GUI_EVENT_NONE; #endif g.EventInfo = NO_EVENT_INFO; #ifndef MINIDLL g.GuiPoint.x = COORD_UNSPECIFIED; g.GuiPoint.y = COORD_UNSPECIFIED; // For these, indexes rather than pointers are stored because handles can become invalid during the // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself): g.GuiWindow = NULL; g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds. g.GuiDefaultWindow = NULL; #endif 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.StringCaseSense = SCS_INSENSITIVE; // AutoIt2 default, and it does seem best. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.AutoTrim = true; // AutoIt2's default, and overall the best default in most cases. _tcscpy(g.FormatFloat, _T("%0.6f")); g.FormatInt = 'D'; g.SendLevel = 0; g.ListLinesIsEnabled = true; g.Encoding = CP_ACP; // For FormatFloat: // I considered storing more than 6 digits to the right of the decimal point (which is the default // for most Unices and MSVC++ it seems). But going beyond that makes things a little weird for many // numbers, due to the inherent imprecision of floating point storage. For example, 83648.4 divided // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with // 20 digits. The extra zeros could be chopped off the end easily enough, but even so, going beyond // 6 digits seems to do more harm than good for the avg. user, overall. A default of 6 is used here // in case other/future compilers have a different default (for backward compatibility, we want // 6 to always be in effect as the default for future releases). } #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel. #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) // 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
tinku99/ahkdll
3b901b76047eb82bef7f2defcc9d749d4b0636b2
WinApi update, fixed some incorrect parameters
diff --git a/source/resources/AutoHotkey.rc b/source/resources/AutoHotkey.rc index d558679..f642808 100644 --- a/source/resources/AutoHotkey.rc +++ b/source/resources/AutoHotkey.rc @@ -1,252 +1,254 @@ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // //#include "afxres.h" #include <winresrc.h> ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 ///////////////////////////////////////////////////////////////////////////// // // RT_MANIFEST // #ifdef EMBED_MANIFEST // VC++ 2005 and later don't require the next line. CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "AutoHotkey.exe.manifest" #endif // TYPELIB // ReleaseDll must be build before DebugDll to update .tlb file #ifdef _USRDLL #ifdef _WIN64 1 TYPELIB "temp\\x64\\ReleaseDll\\AutoHotkey.tlb" #else #ifdef _UNICODE 1 TYPELIB "temp\\Win32\\ReleaseDll\\AutoHotkey.tlb" #else 1 TYPELIB "temp\\Win32\\ReleaseDll(mbcs)\\AutoHotkey.tlb" #endif #endif #endif #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "//#include ""afxres.h""\r\n" "#include <winresrc.h>\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #ifndef MINIDLL ///////////////////////////////////////////////////////////////////////////// // // Menu // IDR_MENU_MAIN MENU BEGIN POPUP "&File" BEGIN MENUITEM "&Reload Script\tCtrl+R", ID_FILE_RELOADSCRIPT MENUITEM "&Edit Script\tCtrl+E", ID_FILE_EDITSCRIPT MENUITEM "&Window Spy", ID_FILE_WINDOWSPY MENUITEM SEPARATOR MENUITEM "&Pause Script\tPause", ID_FILE_PAUSE MENUITEM "&Suspend Hotkeys", ID_FILE_SUSPEND MENUITEM SEPARATOR MENUITEM "E&xit (Terminate Script)", ID_FILE_EXIT END POPUP "&View" BEGIN MENUITEM "&Lines most recently executed\tCtrl+L", ID_VIEW_LINES MENUITEM "&Variables and their contents\tCtrl+V", ID_VIEW_VARIABLES MENUITEM "&Hotkeys and their methods\tCtrl+H", ID_VIEW_HOTKEYS MENUITEM "&Key history and script info\tCtrl+K", ID_VIEW_KEYHISTORY MENUITEM SEPARATOR MENUITEM "&Refresh\tF5", ID_VIEW_REFRESH END POPUP "&Help" BEGIN MENUITEM "&User Manual\tF1", ID_HELP_USERMANUAL MENUITEM "&Web Site", ID_HELP_WEBSITE END END ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_MAIN ICON "icon_main.ico" IDI_SUSPEND ICON "icon_suspend.ico" IDI_PAUSE ICON "icon_pause.ico" IDI_PAUSE_SUSPEND ICON "icon_pause_suspend.ico" IDI_FILETYPE ICON "icon_filetype.ico" IDI_TRAY_WIN9X ICON "icon_tray_win9x.ico" IDI_TRAY_WIN9X_SUSPEND ICON "icon_tray_win9x_suspend.ico" IDI_TRAY ICON "icon_tray.ico" ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_INPUTBOX DIALOGEX 0, 0, 210, 83 STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME CAPTION "Dialog" FONT 10, "MS Shell Dlg", 400, 0, 0x0 BEGIN EDITTEXT IDC_INPUTEDIT,2,51,207,12,ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,51,67,31,12 PUSHBUTTON "Cancel",IDCANCEL,129,67,31,12 LTEXT "Prompt",IDC_INPUTPROMPT,3,2,205,48 END ///////////////////////////////////////////////////////////////////////////// // // Accelerator // IDR_ACCELERATOR1 ACCELERATORS BEGIN VK_F1, ID_HELP_USERMANUAL, VIRTKEY, NOINVERT "H", ID_VIEW_HOTKEYS, VIRTKEY, CONTROL, NOINVERT "K", ID_VIEW_KEYHISTORY, VIRTKEY, CONTROL, NOINVERT "L", ID_VIEW_LINES, VIRTKEY, CONTROL, NOINVERT VK_F5, ID_VIEW_REFRESH, VIRTKEY, NOINVERT "V", ID_VIEW_VARIABLES, VIRTKEY, CONTROL, NOINVERT VK_PAUSE, ID_FILE_PAUSE, VIRTKEY, NOINVERT "E", ID_FILE_EDITSCRIPT, VIRTKEY, CONTROL, NOINVERT "R", ID_FILE_RELOADSCRIPT, VIRTKEY, CONTROL, NOINVERT END #endif ///////////////////////////////////////////////////////////////////////////// // // Version // #include "..\ahkversion.h" #ifdef UNICODE #define AHK_ENC "Unicode" #else #define AHK_ENC "ANSI" #endif #ifdef _WIN64 #define AHK_BIT "64-bit" #else #define AHK_BIT "32-bit" #endif VS_VERSION_INFO VERSIONINFO FILEVERSION AHK_VERSION_N PRODUCTVERSION AHK_VERSION_N FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN #ifdef AUTOHOTKEYSC VALUE "FileDescription", " " VALUE "FileVersion", AHK_VERSION VALUE "InternalName", " " VALUE "LegalCopyright", "" VALUE "OriginalFilename", " " VALUE "ProductName", " " VALUE "ProductVersion", AHK_VERSION #else VALUE "FileDescription", "AutoHotkey_H " AHK_ENC " " AHK_BIT VALUE "FileVersion", AHK_VERSION VALUE "InternalName", "AutoHotkey_H" VALUE "LegalCopyright", "Copyright (C) 2012" #ifdef USRDLL #ifdef MINIDLL VALUE "OriginalFilename", "AutoHotkeyMini.dll" #else VALUE "OriginalFilename", "AutoHotkey.dll" #endif #else VALUE "OriginalFilename", "AutoHotkey.exe" #endif VALUE "ProductName", "AutoHotkey_H" VALUE "ProductVersion", AHK_VERSION #endif END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED +WINAPI RCDATA ".\\source\\resources\\WINAPI.zip" + // AutoHotkey debugging script #ifdef _DEBUG #ifndef _USRDLL //AHK RCDATA "Test\\Test.ahk" #endif #endif \ No newline at end of file diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip index 40a0a81..6f2a4fc 100644 Binary files a/source/resources/WINAPI.zip and b/source/resources/WINAPI.zip differ
tinku99/ahkdll
50a7c0704ad8b1125c7186732f8ddf08a9323304
Bug fix WinApi when func has no parameters
diff --git a/source/util.cpp b/source/util.cpp index acc8354..ecc1c41 100644 --- a/source/util.cpp +++ b/source/util.cpp @@ -2520,634 +2520,634 @@ HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList) } return hresult; } //HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags) //{ // // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP. // // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally // // in case older OSes can ever have it. // HRESULT hresult = !S_OK; // Set default as "failure". // HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme")); // if (hinstTheme) // { // typedef HRESULT (WINAPI *MyEnableThemeDialogTextureType)(HWND, DWORD); // MyEnableThemeDialogTextureType DynEnableThemeDialogTexture = (MyEnableThemeDialogTextureType)GetProcAddress(hinstTheme, "EnableThemeDialogTexture"); // if (DynEnableThemeDialogTexture) // hresult = DynEnableThemeDialogTexture(hwnd, dwFlags); // FreeLibrary(hinstTheme); // } // return hresult; //} LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace) // Replaces any escape sequences in aBuf with their reduced equivalent. For example, if aEscapeChar // is accent, Each `n would become a literal linefeed. aBuf's length should always be the same or // lower than when the process started, so there is no chance of overflow. { LPTSTR cp, cp1; for (cp = aBuf; ; ++cp) // Increment to skip over the symbol just found by the inner for(). { for (; *cp && *cp != aEscapeChar; ++cp); // Find the next escape char. if (!*cp) // end of string. break; cp1 = cp + 1; switch (*cp1) { // Only lowercase is recognized for these: case 'a': *cp1 = '\a'; break; // alert (bell) character case 'b': *cp1 = '\b'; break; // backspace case 'f': *cp1 = '\f'; break; // formfeed case 'n': *cp1 = '\n'; break; // newline case 'r': *cp1 = '\r'; break; // carriage return case 't': *cp1 = '\t'; break; // horizontal tab case 'v': *cp1 = '\v'; break; // vertical tab case 's': // space (not always allowed for backward compatibility reasons). if (aAllowEscapedSpace) *cp1 = ' '; //else do nothing extra, just let the standard action for unrecognized escape sequences. break; // Otherwise, if it's not one of the above, the escape-char is considered to // mark the next character as literal, regardless of what it is. Examples: // `` -> ` // `:: -> :: (effectively) // `; -> ; // `c -> c (i.e. unknown escape sequences resolve to the char after the `) } // Below has a final +1 to include the terminator: tmemmove(cp, cp1, _tcslen(cp1) + 1); } return aBuf; } int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter, int aStartIndex, LPCTSTR aLiteralMap) // Returns the index of the next delimiter, taking into account quotes, parentheses, etc. // If the delimiter is not found, returns the length of aBuf. { bool in_quotes = false; int open_parens = 0; for (int mark = aStartIndex; ; ++mark) { if (aBuf[mark] == aDelimiter) { if (!in_quotes && open_parens <= 0 && !(aLiteralMap && aLiteralMap[mark])) // A delimiting comma other than one in a sub-statement or function. return mark; // Otherwise, its a quoted/literal comma or one in parentheses (such as function-call). continue; } switch (aBuf[mark]) { case '"': // There are sections similar this one later below; so see them for comments. in_quotes = !in_quotes; break; case '(': // For our purpose, "(", "[" and "{" can be treated the same. case '[': // If they aren't balanced properly, a later stage will detect it. case '{': // if (!in_quotes) // Literal parentheses inside a quoted string should not be counted for this purpose. ++open_parens; break; case ')': case ']': case '}': if (!in_quotes) --open_parens; // If this makes it negative, validation later on will catch the syntax error. break; case '\0': // Reached the end of the string without finding a delimiter. Return the // index of the null-terminator since that's typically what the caller wants. return mark; //default: some other character; just have the loop skip over it. } } } bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch) // Checks if aStr exists in aList (which is a comma-separated list). // If aStr is blank, aList must start with a delimiting comma for there to be a match. { // Must use a temp. buffer because otherwise there's no easy way to properly match upon strings // such as the following: // if var in string,,with,,literal,,commas TCHAR buf[LINE_SIZE]; TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1; // v1.0.48.01: Performance improved by Lexikos. for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList. { for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer. { if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,). { ++next_field; if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field. break; // Otherwise it's ",," and next_field now points at the second comma; so copy that comma // over as a literal comma then continue copying. } *cp = *next_field; } // The end of this field has been reached (or reached the capacity of the buffer), so terminate the string // in the buffer. *cp = '\0'; if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc { if (aFindExactMatch) { if (!g_tcscmp(aStr, buf)) // Match found return true; } else // Substring match if (g_tcsstr(aStr, buf)) // Match found return true; } else // First item in the list is the empty string. if (aFindExactMatch) // In this case, this is a match if aStr is also blank. { if (!*aStr) return true; } else // Empty string is always found as a substring in any other string. return true; } // for() return false; // No match found. } LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen) { // For each character in aStr: for ( ; *aStr; ++aStr) // For each needle: for (int i = 0; i < aNeedleCount; ++i) // For each character in this needle: for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos) { if (!*needle_pos) { // All characters in needle matched aStr at this position, so we've // found our string. If this needle is empty, it implicitly matches // at the first position in the string. aFoundLen = needle_pos - aNeedle[i]; return aStr; } // Otherwise, we haven't reached the end of the needle. If we've reached // the end of aStr, *str_pos and *needle_pos won't match, so the check // below will break out of the loop. if (*needle_pos != *str_pos) // Not a match: continue on to the next needle, or the next starting // position in aStr if this is the last needle. break; } // If the above loops completed without returning, no matches were found. return NULL; } short IsDefaultType(LPTSTR aTypeDef){ static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ") #ifndef _WIN64 ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ") #else ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ") #endif ,_T("") #ifdef _WIN64 ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ") #else ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #endif ,_T(""),_T(""),_T("") #ifdef _WIN64 ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #else ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ") #endif }; for (int i=0;i<8;i++) { if (tcscasestr(sTypeDef[i],aTypeDef)) return i + 1; } // type was not found return NULL; } ResultType LoadDllFunction(LPTSTR parameter, LPTSTR aBuf) { LPTSTR aFuncName = omit_leading_whitespace(parameter); // backup current function // Func currentfunc = **g_script.mFunc; if (!(parameter = _tcschr(parameter, ',')) || !*parameter) return g_script.ScriptError(ERR_PARAM2_REQUIRED, aBuf); else parameter++; if (_tcschr(aFuncName, ',')) *(_tcschr(aFuncName, ',')) = '\0'; ltrim(parameter); int insert_pos; Func *found_func = g_script.FindFunc(aFuncName, _tcslen(aFuncName), &insert_pos); if (found_func) return g_script.ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined." else if (!(found_func = g_script.AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos))) return FAIL; // It already displayed the error. void *function = NULL; // Will hold the address of the function to be called. found_func->mBIF = (BuiltInFunctionType)BIF_DllImport; found_func->mIsBuiltIn = true; found_func->mMinParams = 0; TCHAR buf[MAX_PATH]; size_t space_remaining = LINE_SIZE - (parameter - aBuf); if (tcscasestr(parameter, _T("%A_ScriptDir%"))) { BIV_ScriptDir(buf, _T("A_ScriptDir")); StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis. { BIV_SpecialFolderPath(buf, _T("A_AppData")); StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04. { BIV_SpecialFolderPath(buf, _T("A_AppDataCommon")); StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04. { BIV_AhkPath(buf, _T("A_AhkPath")); StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkDir%"))) // v1.0.45.04. { BIV_AhkDir(buf, _T("A_AhkDir")); StrReplace(parameter, _T("%A_AhkDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllDir%"))) // v1.0.45.04. { BIV_DllDir(buf, _T("A_DllDir")); StrReplace(parameter, _T("%A_DllDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04. { BIV_DllPath(buf, _T("A_DllPath")); StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (_tcschr(parameter, '%')) { return g_script.ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_AhkDir% %A_DllPath% %A_DllDir% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter); } // terminate dll\function name, find it and jump to next parameter if (_tcschr(parameter, ',')) *(_tcschr(parameter, ',')) = '\0'; function = (void*)ATOI64(parameter); if (!function) { LPTSTR dll_name = _tcsrchr(parameter, '\\'); if (dll_name) { *dll_name = '\0'; if (!GetModuleHandle(parameter)) LoadLibrary(parameter); *dll_name = '\\'; } function = (void*)GetDllProcAddress(parameter); } if (!function) return g_script.ScriptError(ERR_NONEXISTENT_FUNCTION, parameter); parameter = parameter + _tcslen(parameter) + 1; LPTSTR parm = SimpleHeap::Malloc(parameter); bool has_return = false; int aParamCount = ATOI(parm) ? 0 : 1; if (*parm) for (; _tcschr(parameter, ','); aParamCount++) { if (parameter = _tcschr(parameter, ',')) parameter++; } if (*parm && aParamCount < 1) return g_script.ScriptError(ERR_PARAM3_REQUIRED, aBuf); // Determine the type of return value. DYNAPARM *return_attrib = (DYNAPARM*)SimpleHeap::Malloc(sizeof(DYNAPARM)); memset(return_attrib, 0, sizeof(DYNAPARM)); // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (!(aParamCount % 2)) // Even number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib->type = DLL_ARG_INT; else { // Check validity of this arg's return type: LPTSTR return_type_string[2]; return_type_string[0] = parameter; return_type_string[1] = NULL; // Added in 1.0.48. // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } ConvertDllArgType(return_type_string, *return_attrib); if (return_attrib->type == DLL_ARG_INVALID) return CONDITION_FALSE; has_return = true; has_valid_return_type: aParamCount--; #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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount / 2; // Might provide one extra due to first/last params, which is inconsequential. DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL; DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif SimpleHeap::Malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. LPTSTR this_param; for (arg_count = 0, i = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { this_param = _tcschr(parm, ','); *this_param = '\0'; this_param++; arg_type_string[0] = parm; // It will be detected as invalid below. arg_type_string[1] = NULL; //ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param_def[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (ATOI64(this_param)) { // 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. return CONDITION_FALSE; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = 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 forget to call VarSetCapacity before passing a buffer 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 (ATOI64(this_param)) return CONDITION_FALSE; // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar, CStringWCharFromChar)(this_param); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. this_dyna_param.value_double = ATOF(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_INVALID: return CONDITION_FALSE; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !ATOI64(this_param)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(this_param); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ATOI64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) parm = _tcschr(this_param,',') + 1; } // for() each arg. - if (has_return) + if (has_return && aParamCount) *(this_param) = '\0'; found_func->mClass = (Object*)function; found_func->mParamCount = arg_count; found_func->mVar = (Var**)return_attrib; found_func->mStaticVar = (Var**)pStr; found_func->mLazyVar = (Var**)dyna_param_def; found_func->mParam = (FuncParam*)dyna_param; #ifdef WIN32_PLATFORM found_func->mVarCount = dll_call_mode; #endif return CONDITION_TRUE; } DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression { unsigned int hdrsz = 20; TCHAR pw[1024] = {0}; if (pwd && pwd[0]) for(unsigned int i = 0;pwd[i];i++) pw[i] = (TCHAR)*pwd[i]; ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8); DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16); DWORD hash; BYTE *aDataEncrypted = NULL; HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4); if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4)) { HUNZIP huz; ZIPENTRY ze; DWORD result; ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12); aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE); if (aDataBuf) { if (aSizeEncrypted) { typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*); HMODULE advapi32 = LoadLibrary(_T("advapi32.dll")); MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt"); LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE); DWORD aSizeEncryptedString = aSizeEncrypted; DWORD aSizeEncryptedTemp = aSizeEncrypted; HCRYPTPROV hProv; HCRYPTKEY hKey; HCRYPTHASH hHash; CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT); CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash); CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0); CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey); CryptDestroyHash(hHash); memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted); Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL); if (aSizeEncryptedTemp == 0) { // incorrect password VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL); VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE); CryptDestroyKey(hKey); CryptReleaseContext(hProv,0); if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } } else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); return 0; } ze.CompressedSize = aSizeDeCompressed; ze.UncompressedSize = aSizeDeCompressed; if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY))) VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); else { closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return aSizeDeCompressed; } closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); } } return 0; } #ifndef MINIDLL LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs) { // Disable all hooks to avoid system/mouse freeze if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && pExceptionPtrs->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE) AddRemoveHooks(0); return EXCEPTION_CONTINUE_SEARCH; } #endif #if defined(_MSC_VER) && defined(_DEBUG) void OutputDebugStringFormat(LPCTSTR fmt, ...) { CString sMsg; va_list ap; va_start(ap, fmt); sMsg.FormatV(fmt, ap); OutputDebugString(sMsg); } #endif
tinku99/ahkdll
1301393cb2f4a1278cb0898ed97f8c1ffefa4a3c
Winapi Functions same as ahk func are now Sleep_, SendMessage_,SendInput_...
diff --git a/source/MemoryModule.cpp b/source/MemoryModule.cpp index 918dedd..ebd5877 100644 --- a/source/MemoryModule.cpp +++ b/source/MemoryModule.cpp @@ -1,623 +1,623 @@ /* * Memory DLL loading code * Version 0.0.3 * * Copyright (c) 2004-2013 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2013 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #include "stdafx.h" // pre-compiled headers #include "MemoryModule.h" #include "globaldata.h" // for access to many global vars #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif #include <windows.h> #include <winnt.h> #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif #include "MemoryModule.h" typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); typedef HANDLE (WINAPI * MyCreateActCtx)(PCACTCTXA); typedef HANDLE (WINAPI * MyDeactivateActCtx)(DWORD,ULONG_PTR); typedef BOOL (WINAPI * MyActivateActCtx)(HANDLE,ULONG_PTR*); HMODULE libkernel32 = LoadLibrary(_T("kernel32.dll")); MyCreateActCtx _CreateActCtxA = (MyCreateActCtx)GetProcAddress(libkernel32,"CreateActCtxA"); MyDeactivateActCtx _DeactivateActCtx = (MyDeactivateActCtx)GetProcAddress(libkernel32,"DeactivateActCtx"); MyActivateActCtx _ActivateActCtx = (MyActivateActCtx)GetProcAddress(libkernel32,"ActivateActCtx"); #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen((const char *) tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugStringA(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); - section->Misc.PhysicalAddress = (DWORD) (POINTER_TYPE) dest; + section->Misc.PhysicalAddress = ((DWORD)(((POINTER_TYPE)(dest)) & 0xffffffff)); memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); - section->Misc.PhysicalAddress = (DWORD) (POINTER_TYPE) dest; + section->Misc.PhysicalAddress = ((DWORD)(((POINTER_TYPE)(dest)) & 0xffffffff)); } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_EXECUTE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags #ifdef DEBUG_OUTPUT if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) OutputLastError("Error protecting memory page"); #else VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect); #endif } } #ifndef _WIN64 #undef imageOffset #endif } static void ExecuteTLS(PMEMORYMODULE module) { unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_TLS); if (directory->VirtualAddress > 0) { PIMAGE_TLS_DIRECTORY tls = (PIMAGE_TLS_DIRECTORY) (codeBase + directory->VirtualAddress); PIMAGE_TLS_CALLBACK* callback = (PIMAGE_TLS_CALLBACK *) tls->AddressOfCallBacks; if (callback) { while (*callback) { (*callback)((LPVOID) codeBase, DLL_PROCESS_ATTACH, NULL); callback++; } } } } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); *patchAddrHL += (DWORD) delta; break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += (ULONGLONG) delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result=1; unsigned char *codeBase = module->codeBase; HCUSTOMMODULE *tmp; ULONG_PTR lpCookie = NULL; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); PIMAGE_DATA_DIRECTORY resource = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_RESOURCE); if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); // Following will be used to resolve manifest in module if (resource->Size) { PIMAGE_RESOURCE_DIRECTORY resDir = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + resource->VirtualAddress); PIMAGE_RESOURCE_DIRECTORY resDirTemp; PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY)); PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntryTemp; PIMAGE_RESOURCE_DATA_ENTRY resDataEntry; // ACTCTX Structure, not used members must be set to 0! ACTCTXA actctx ={0,0,0,0,0,0,0,0,0}; actctx.cbSize = sizeof(actctx); HANDLE hActCtx; // Path to temp directory + our temporary file name CHAR buf[MAX_PATH]; DWORD tempPathLength = GetTempPathA(MAX_PATH, buf); memcpy(buf + tempPathLength,"AutoHotkey.MemoryModule.temp.manifest",38); actctx.lpSource = buf; // Enumerate Resources int i = 0; if (_CreateActCtxA != NULL) for (;i < resDir->NumberOfIdEntries + resDir->NumberOfNamedEntries;i++) { // Resolve current entry resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY) + (i*sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))); // If entry is directory and Id is 24 = RT_MANIFEST if (resDirEntry->DataIsDirectory && resDirEntry->Id == 24) { //resDirTemp = (PIMAGE_RESOURCE_DIRECTORY)((char*)resDir + (resDirEntry->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntry->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDirTemp = (PIMAGE_RESOURCE_DIRECTORY) ((char*)resDir + (resDirEntryTemp->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntryTemp->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDataEntry = (PIMAGE_RESOURCE_DATA_ENTRY) ((char*)resDir + (resDirEntryTemp->OffsetToData)); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after CreateActCtx has been called. HANDLE hFile = CreateFileA(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif break; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,(codeBase + resDataEntry->OffsetToData),resDataEntry->Size,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif break; //failed to write data, continue and try loading } hActCtx = _CreateActCtxA(&actctx); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileA(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); if (hActCtx == INVALID_HANDLE_VALUE) break; //failed to create context, continue and try loading _ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway break; // Break since a dll can have only 1 manifest } } } for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HCUSTOMMODULE handle; handle = module->loadLibrary((LPCSTR) (codeBase + importDesc->Name), module->userdata); if (handle == NULL) { SetLastError(ERROR_MOD_NOT_FOUND); result = 0; break; } tmp = (HCUSTOMMODULE *) realloc(module->modules, (module->numModules+1)*(sizeof(HCUSTOMMODULE))); if (tmp == NULL) { module->freeLibrary(handle, module->userdata); SetLastError(ERROR_OUTOFMEMORY); result = 0; break; } module->modules = tmp; module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = module->getProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef), module->userdata); } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = module->getProcAddress(handle, (LPCSTR)&thunkData->Name, module->userdata); } if (*funcRef == 0) { result = 0; break; } } if (!result) { module->freeLibrary(handle, module->userdata); SetLastError(ERROR_PROC_NOT_FOUND); break; } } } if (_DeactivateActCtx && lpCookie) _DeactivateActCtx(NULL,lpCookie); return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { return MemoryLoadLibraryEx(data, _LoadLibrary, _GetProcAddress, _FreeLibrary, NULL); } HMEMORYMODULE MemoryLoadLibraryEx(const void *data, CustomLoadLibraryFunc loadLibrary, CustomGetProcAddressFunc getProcAddress, CustomFreeLibraryFunc freeLibrary, void *userdata) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } // reserve memory for image of library // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (code == NULL) { SetLastError(ERROR_OUTOFMEMORY); return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); if (result == NULL) { SetLastError(ERROR_OUTOFMEMORY); VirtualFree(code, 0, MEM_RELEASE); return NULL; } result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; result->loadLibrary = loadLibrary; result->getProcAddress = getProcAddress; result->freeLibrary = freeLibrary; result->userdata = userdata; // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // copy PE header to code memcpy(headers, dos_header, old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections((const unsigned char*) data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // TLS callbacks are executed BEFORE the main loading ExecuteTLS(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, result); if (!successfull) { SetLastError(ERROR_DLL_INIT_FAILED); goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, LPCSTR name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module != NULL) { if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } if (module->modules != NULL) { // free previously opened libraries for (i=0; i<module->numModules; i++) { if (module->modules[i] != NULL) { module->freeLibrary(module->modules[i], module->userdata); } } free(module->modules); } if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); } HeapFree(GetProcessHeap(), 0, module); } } #define DEFAULT_LANGUAGE MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) HMEMORYRSRC MemoryFindResource(HMEMORYMODULE module, LPCTSTR name, LPCTSTR type) { return MemoryFindResourceEx(module, name, type, DEFAULT_LANGUAGE); } static PIMAGE_RESOURCE_DIRECTORY_ENTRY _MemorySearchResourceEntry( void *root, PIMAGE_RESOURCE_DIRECTORY resources, LPCTSTR key) { PIMAGE_RESOURCE_DIRECTORY_ENTRY entries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) (resources + 1); PIMAGE_RESOURCE_DIRECTORY_ENTRY result = NULL; DWORD start; DWORD end; DWORD middle; if (!IS_INTRESOURCE(key) && key[0] == TEXT('#')) { // special case: resource id given as string TCHAR *endpos = NULL; #if defined(UNICODE) long int tmpkey = (WORD) wcstol((TCHAR *) &key[1], &endpos, 10); #else diff --git a/source/keyboard_mouse.cpp b/source/keyboard_mouse.cpp index 6daf5e0..f24d422 100644 --- a/source/keyboard_mouse.cpp +++ b/source/keyboard_mouse.cpp @@ -3877,514 +3877,514 @@ LPTSTR SCtoKeyName(sc_type aSC, LPTSTR aBuf, int aBufSize, bool aUseFallback) LPTSTR VKtoKeyName(vk_type aVK, LPTSTR aBuf, int aBufSize, bool aUseFallback) // aBufSize is an int so that any negative values passed in from caller are not lost. // Caller may omit aSC and it will be derived if needed. { for (int i = 0; i < g_key_to_vk_count; ++i) { if (g_key_to_vk[i].vk == aVK) { tcslcpy(aBuf, g_key_to_vk[i].key_name, aBufSize); return aBuf; } } // Since above didn't return, no match was found. Try to map it to // a character or use the default format for an unknown key code: if (*aBuf = (TCHAR)MapVirtualKey(aVK, MAPVK_VK_TO_CHAR)) aBuf[1] = '\0'; else if (aUseFallback && aVK) sntprintf(aBuf, aBufSize, _T("vk%02X"), aVK); else *aBuf = '\0'; return aBuf; } sc_type TextToSC(LPTSTR aText) { if (!*aText) return 0; for (int i = 0; i < g_key_to_sc_count; ++i) if (!_tcsicmp(g_key_to_sc[i].key_name, aText)) return g_key_to_sc[i].sc; // Do this only after the above, in case any valid key names ever start with SC: if (ctoupper(*aText) == 'S' && ctoupper(*(aText + 1)) == 'C') return (sc_type)_tcstol(aText + 2, NULL, 16); // Convert from hex. return 0; // Indicate "not found". } vk_type TextToVK(LPTSTR aText, modLR_type *pModifiersLR, bool aExcludeThoseHandledByScanCode, bool aAllowExplicitVK , HKL aKeybdLayout) // If modifiers_p is non-NULL, place the modifiers that are needed to realize the key in there. // e.g. M is really +m (shift-m), # is really shift-3. // HOWEVER, this function does not completely overwrite the contents of pModifiersLR; instead, it just // adds the required modifiers into whatever is already there. { if (!*aText) return 0; // Don't trim() aText or modify it because that will mess up the caller who expects it to be unchanged. // Instead, for now, just check it as-is. The only extra whitespace that should exist, due to trimming // of text during load, is that on either side of the COMPOSITE_DELIMITER (e.g. " then "). if (!aText[1]) // _tcslen(aText) == 1 return CharToVKAndModifiers(*aText, pModifiersLR, aKeybdLayout); // Making this a function simplifies things because it can do early return, etc. if (aAllowExplicitVK && ctoupper(aText[0]) == 'V' && ctoupper(aText[1]) == 'K') return (vk_type)_tcstol(aText + 2, NULL, 16); // Convert from hex. for (int i = 0; i < g_key_to_vk_count; ++i) if (!_tcsicmp(g_key_to_vk[i].key_name, aText)) return g_key_to_vk[i].vk; if (aExcludeThoseHandledByScanCode) return 0; // Zero is not a valid virtual key, so it should be a safe failure indicator. // Otherwise check if aText is the name of a key handled by scan code and if so, map that // scan code to its corresponding virtual key: sc_type sc = TextToSC(aText); return sc ? sc_to_vk(sc) : 0; } vk_type CharToVKAndModifiers(TCHAR aChar, modLR_type *pModifiersLR, HKL aKeybdLayout) // If non-NULL, pModifiersLR contains the initial set of modifiers provided by the caller, to which // we add any extra modifiers required to realize aChar. { // For v1.0.25.12, it seems best to avoid the many recent problems with linefeed (`n) being sent // as Ctrl+Enter by changing it to always send a plain Enter, just like carriage return (`r). if (aChar == '\n') return VK_RETURN; // Otherwise: SHORT mod_plus_vk = VkKeyScanEx(aChar, aKeybdLayout); // v1.0.44.03: Benchmark shows that VkKeyScanEx() is the same speed as VkKeyScan() when the layout has been pre-fetched. vk_type vk = LOBYTE(mod_plus_vk); char keyscan_modifiers = HIBYTE(mod_plus_vk); if (keyscan_modifiers == -1 && vk == (UCHAR)-1) // No translation could be made. return 0; if (keyscan_modifiers & 0x38) // "The Hankaku key is pressed" or either of the "Reserved" state bits (for instance, used by Neo2 keyboard layout). // Callers expect failure in this case so that a fallback method can be used. return 0; // For v1.0.35, pModifiersLR was changed to modLR vs. mod so that AltGr keys such as backslash and // '{' are supported on layouts such as German when sending to apps such as Putty that are fussy about // which ALT key is held down to produce the character. The following section detects AltGr by the // assuming that any character that requires both CTRL and ALT (with optional SHIFT) to be held // down is in fact an AltGr key (I don't think there are any that aren't AltGr in this case, but // confirmation would be nice). Also, this is not done for Win9x because the distinction between // right and left-alt is not well-supported and it might do more harm than good (testing is // needed on fussy apps like Putty on Win9x). UPDATE: Windows NT4 is now excluded from this // change because apparently it wants the left Alt key's virtual key and not the right's (though // perhaps it would prefer the right scan code vs. the left in apps such as Putty, but until that // is proven, the complexity is not added here). Otherwise, on French and other layouts on NT4, // AltGr-produced characters such as backslash do not get sent properly. In hindsight, this is // not surprising because the keyboard hook also receives neutral modifier keys on NT4 rather than // a more specific left/right key. // The win docs for VkKeyScan() are a bit confusing, referring to flag "bits" when it should really // say flag "values". In addition, it seems that these flag values are incompatible with // MOD_ALT, MOD_SHIFT, and MOD_CONTROL, so they must be translated: if (pModifiersLR) // The caller wants this info added to the output param. { // Best not to reset this value because some callers want to retain what was in it before, // merely merging these new values into it: //*pModifiers = 0; if ((keyscan_modifiers & 0x06) == 0x06 && g_os.IsWin2000orLater()) // 0x06 means "requires/includes AltGr". { // v1.0.35: The critical difference below is right vs. left ALT. Must not include MOD_LCONTROL // because simulating the RAlt keystroke on these keyboard layouts will automatically // press LControl down. *pModifiersLR |= MOD_RALT; } else // Do normal/default translation. { // v1.0.40: If caller-supplied modifiers already include the right-side key, no need to // add the left-side key (avoids unnecessary keystrokes). if ( (keyscan_modifiers & 0x02) && !(*pModifiersLR & (MOD_LCONTROL|MOD_RCONTROL)) ) *pModifiersLR |= MOD_LCONTROL; // Must not be done if requires_altgr==true, see above. if ( (keyscan_modifiers & 0x04) && !(*pModifiersLR & (MOD_LALT|MOD_RALT)) ) *pModifiersLR |= MOD_LALT; } // v1.0.36.06: Done unconditionally because presence of AltGr should not preclude the presence of Shift. // v1.0.40: If caller-supplied modifiers already contains MOD_RSHIFT, no need to add LSHIFT (avoids // unnecessary keystrokes). if ( (keyscan_modifiers & 0x01) && !(*pModifiersLR & (MOD_LSHIFT|MOD_RSHIFT)) ) *pModifiersLR |= MOD_LSHIFT; } return vk; } vk_type TextToSpecial(LPTSTR aText, size_t aTextLength, KeyEventTypes &aEventType, modLR_type &aModifiersLR , bool aUpdatePersistent) // Returns vk for key-down, negative vk for key-up, or zero if no translation. // We also update whatever's in *pModifiers and *pModifiersLR to reflect the type of key-action // specified in <aText>. This makes it so that {altdown}{esc}{altup} behaves the same as !{esc}. // Note that things like LShiftDown are not supported because: 1) they are rarely needed; and 2) // they can be down via "lshift down". { if (!tcslicmp(aText, _T("ALTDOWN"), aTextLength)) { if (aUpdatePersistent) if (!(aModifiersLR & (MOD_LALT | MOD_RALT))) // i.e. do nothing if either left or right is already present. aModifiersLR |= MOD_LALT; // If neither is down, use the left one because it's more compatible. aEventType = KEYDOWN; return VK_MENU; } if (!tcslicmp(aText, _T("ALTUP"), aTextLength)) { // Unlike for Lwin/Rwin, it seems best to have these neutral keys (e.g. ALT vs. LALT or RALT) // restore either or both of the ALT keys into the up position. The user can use {LAlt Up} // to be more specific and avoid this behavior: if (aUpdatePersistent) aModifiersLR &= ~(MOD_LALT | MOD_RALT); aEventType = KEYUP; return VK_MENU; } if (!tcslicmp(aText, _T("SHIFTDOWN"), aTextLength)) { if (aUpdatePersistent) if (!(aModifiersLR & (MOD_LSHIFT | MOD_RSHIFT))) // i.e. do nothing if either left or right is already present. aModifiersLR |= MOD_LSHIFT; // If neither is down, use the left one because it's more compatible. aEventType = KEYDOWN; return VK_SHIFT; } if (!tcslicmp(aText, _T("SHIFTUP"), aTextLength)) { if (aUpdatePersistent) aModifiersLR &= ~(MOD_LSHIFT | MOD_RSHIFT); // See "ALTUP" for explanation. aEventType = KEYUP; return VK_SHIFT; } if (!tcslicmp(aText, _T("CTRLDOWN"), aTextLength) || !tcslicmp(aText, _T("CONTROLDOWN"), aTextLength)) { if (aUpdatePersistent) if (!(aModifiersLR & (MOD_LCONTROL | MOD_RCONTROL))) // i.e. do nothing if either left or right is already present. aModifiersLR |= MOD_LCONTROL; // If neither is down, use the left one because it's more compatible. aEventType = KEYDOWN; return VK_CONTROL; } if (!tcslicmp(aText, _T("CTRLUP"), aTextLength) || !tcslicmp(aText, _T("CONTROLUP"), aTextLength)) { if (aUpdatePersistent) aModifiersLR &= ~(MOD_LCONTROL | MOD_RCONTROL); // See "ALTUP" for explanation. aEventType = KEYUP; return VK_CONTROL; } if (!tcslicmp(aText, _T("LWINDOWN"), aTextLength)) { if (aUpdatePersistent) aModifiersLR |= MOD_LWIN; aEventType = KEYDOWN; return VK_LWIN; } if (!tcslicmp(aText, _T("LWINUP"), aTextLength)) { if (aUpdatePersistent) aModifiersLR &= ~MOD_LWIN; aEventType = KEYUP; return VK_LWIN; } if (!tcslicmp(aText, _T("RWINDOWN"), aTextLength)) { if (aUpdatePersistent) aModifiersLR |= MOD_RWIN; aEventType = KEYDOWN; return VK_RWIN; } if (!tcslicmp(aText, _T("RWINUP"), aTextLength)) { if (aUpdatePersistent) aModifiersLR &= ~MOD_RWIN; aEventType = KEYUP; return VK_RWIN; } // Otherwise, leave aEventType unchanged and return zero to indicate failure: return 0; } #ifdef ENABLE_KEY_HISTORY_FILE ResultType KeyHistoryToFile(LPTSTR aFilespec, char aType, bool aKeyUp, vk_type aVK, sc_type aSC) { static TCHAR sTargetFilespec[MAX_PATH] = _T(""); static FILE *fp = NULL; static HWND last_foreground_window = NULL; static DWORD last_tickcount = GetTickCount(); if (!g_KeyHistory) // Since key history is disabled, keys are not being tracked by the hook, so there's nothing to log. return OK; // Files should not need to be closed since they would never have been opened in the first place. if (!aFilespec && !aVK && !aSC) // Caller is signaling to close the file if it's open. { if (fp) { fclose(fp); fp = NULL; } return OK; } if (aFilespec && *aFilespec && lstrcmpi(aFilespec, sTargetFilespec)) // Target filename has changed. { if (fp) { fclose(fp); fp = NULL; // To indicate to future calls to this function that it's closed. } tcslcpy(sTargetFilespec, aFilespec, _countof(sTargetFilespec)); } if (!aVK && !aSC) // Caller didn't want us to log anything this time. return OK; if (!*sTargetFilespec) return OK; // No target filename has ever been specified, so don't even attempt to open the file. if (!aVK) aVK = sc_to_vk(aSC); else if (!aSC) aSC = vk_to_sc(aVK); TCHAR buf[2048] = _T(""), win_title[1024] = _T("<Init>"), key_name[128] = _T(""); HWND curr_foreground_window = GetForegroundWindow(); DWORD curr_tickcount = GetTickCount(); bool log_changed_window = (curr_foreground_window != last_foreground_window); if (log_changed_window) { if (curr_foreground_window) GetWindowText(curr_foreground_window, win_title, _countof(win_title)); else tcslcpy(win_title, _T("<None>"), _countof(win_title)); last_foreground_window = curr_foreground_window; } sntprintf(buf, _countof(buf), _T("%02X") _T("\t%03X") _T("\t%0.2f") _T("\t%c") _T("\t%c") _T("\t%s") _T("%s%s\n") , aVK, aSC , (float)(curr_tickcount - last_tickcount) / (float)1000 , aType , aKeyUp ? 'u' : 'd' , GetKeyName(aVK, aSC, key_name, sizeof(key_name)) , log_changed_window ? _T("\t") : _T("") , log_changed_window ? win_title : _T("") ); last_tickcount = curr_tickcount; if (!fp) if ( !(fp = _tfopen(sTargetFilespec, _T("a"))) ) return OK; _fputts(buf, fp); return OK; } #endif LPTSTR GetKeyName(vk_type aVK, sc_type aSC, LPTSTR aBuf, int aBufSize, LPTSTR aDefault) // aBufSize is an int so that any negative values passed in from caller are not lost. // Caller has ensured that aBuf isn't NULL. { if (aBufSize < 3) return aBuf; *aBuf = '\0'; // Set default. if (!aVK && !aSC) return aBuf; if (!aVK) aVK = sc_to_vk(aSC); else if (!aSC) aSC = vk_to_sc(aVK); // Check SC first to properly differentiate between Home/NumpadHome, End/NumpadEnd, etc. // v1.0.43: WheelDown/Up store the notch/turn count in SC, so don't consider that to be a valid SC. if (aSC && !IS_WHEEL_VK(aVK)) { if (*SCtoKeyName(aSC, aBuf, aBufSize, false)) return aBuf; // Otherwise this key is probably one we can handle by VK. } if (*VKtoKeyName(aVK, aBuf, aBufSize, false)) return aBuf; // Since this key is unrecognized, return the caller-supplied default value. return aDefault; } sc_type vk_to_sc(vk_type aVK, bool aReturnSecondary) // For v1.0.37.03, vk_to_sc() was converted into a function rather than being an array because if the // script's keyboard layout changes while it's running, the array would get out-of-date. // If caller passes true for aReturnSecondary, the non-primary scan code will be returned for // virtual keys that two scan codes (if there's only one scan code, callers rely on zero being returned). { // Try to minimize the number mappings done manually because MapVirtualKey is a more reliable // way to get the mapping if user has non-standard or custom keyboard layout. sc_type sc = 0; switch (aVK) { // Yield a manually translation for virtual keys that MapVirtualKey() doesn't support or for which it // doesn't yield consistent result (such as Win9x supporting only SHIFT rather than VK_LSHIFT/VK_RSHIFT). case VK_LSHIFT: sc = SC_LSHIFT; break; // Modifiers are listed first for performance. case VK_RSHIFT: sc = SC_RSHIFT; break; case VK_LCONTROL: sc = SC_LCONTROL; break; case VK_RCONTROL: sc = SC_RCONTROL; break; case VK_LMENU: sc = SC_LALT; break; case VK_RMENU: sc = SC_RALT; break; case VK_LWIN: sc = SC_LWIN; break; // Earliest versions of Win95/NT might not support these, so map them manually. case VK_RWIN: sc = SC_RWIN; break; // // According to http://support.microsoft.com/default.aspx?scid=kb;en-us;72583 // most or all numeric keypad keys cannot be mapped reliably under any OS. The article is // a little unclear about which direction, if any, that MapVirtualKey() does work in for // the numpad keys, so for peace-of-mind map them all manually for now: case VK_NUMPAD0: sc = SC_NUMPAD0; break; case VK_NUMPAD1: sc = SC_NUMPAD1; break; case VK_NUMPAD2: sc = SC_NUMPAD2; break; case VK_NUMPAD3: sc = SC_NUMPAD3; break; case VK_NUMPAD4: sc = SC_NUMPAD4; break; case VK_NUMPAD5: sc = SC_NUMPAD5; break; case VK_NUMPAD6: sc = SC_NUMPAD6; break; case VK_NUMPAD7: sc = SC_NUMPAD7; break; case VK_NUMPAD8: sc = SC_NUMPAD8; break; case VK_NUMPAD9: sc = SC_NUMPAD9; break; case VK_DECIMAL: sc = SC_NUMPADDOT; break; case VK_NUMLOCK: sc = SC_NUMLOCK; break; case VK_DIVIDE: sc = SC_NUMPADDIV; break; case VK_MULTIPLY: sc = SC_NUMPADMULT; break; case VK_SUBTRACT: sc = SC_NUMPADSUB; break; case VK_ADD: sc = SC_NUMPADADD; break; } if (sc) // Above found a match. return aReturnSecondary ? 0 : sc; // Callers rely on zero being returned for VKs that don't have secondary SCs. // Use the OS API's MapVirtualKey() to resolve any not manually done above: if ( !(sc = MapVirtualKey(aVK, 0)) ) return 0; // Indicate "no mapping". // Turn on the extended flag for those that need it. // Because MapVirtualKey can only accept (and return) naked scan codes (the low-order byte), // handle extended scan codes that have a non-extended counterpart manually. // Older comment: MapVirtualKey() should include 0xE0 in HIBYTE if key is extended, BUT IT DOESN'T. // There doesn't appear to be any built-in function to determine whether a vk's scan code // is extended or not. See MSDN topic "keyboard input" for the below list. // Note: NumpadEnter is probably the only extended key that doesn't have a unique VK of its own. // So in that case, probably safest not to set the extended flag. To send a true NumpadEnter, // as well as a true NumPadDown and any other key that shares the same VK with another, the // caller should specify the sc param to circumvent the need for KeyEvent() to use the below: switch (aVK) { case VK_APPS: // Application key on keyboards with LWIN/RWIN/Apps. Not listed in MSDN as "extended"? case VK_CANCEL: // Ctrl-break case VK_SNAPSHOT: // PrintScreen case VK_DIVIDE: // NumpadDivide (slash) case VK_NUMLOCK: // Below are extended but were already handled and returned from higher above: //case VK_LWIN: //case VK_RWIN: //case VK_RMENU: //case VK_RCONTROL: //case VK_RSHIFT: // WinXP needs this to be extended for keybd_event() to work properly. sc |= 0x0100; break; // The following virtual keys have more than one physical key, and thus more than one scan code. // If the caller passed true for aReturnSecondary, the extended version of the scan code will be // returned (all of the following VKs have two SCs): case VK_RETURN: case VK_INSERT: case VK_DELETE: case VK_PRIOR: // PgUp case VK_NEXT: // PgDn case VK_HOME: case VK_END: case VK_UP: case VK_DOWN: case VK_LEFT: case VK_RIGHT: return aReturnSecondary ? (sc | 0x0100) : sc; // Below relies on the fact that these cases return early. } // Since above didn't return, if aReturnSecondary==true, return 0 to indicate "no secondary SC for this VK". return aReturnSecondary ? 0 : sc; // Callers rely on zero being returned for VKs that don't have secondary SCs. } vk_type sc_to_vk(sc_type aSC) { // These are mapped manually because MapVirtualKey() doesn't support them correctly, at least // on some -- if not all -- OSs. The main app also relies upon the values assigned below to // determine which keys should be handled by scan code rather than vk: switch (aSC) { // Even though neither of the SHIFT keys are extended -- and thus could be mapped with MapVirtualKey() // -- it seems better to define them explicitly because under Win9x (maybe just Win95). // I'm pretty sure MapVirtualKey() would return VK_SHIFT instead of the left/right VK. case SC_LSHIFT: return VK_LSHIFT; // Modifiers are listed first for performance. case SC_RSHIFT: return VK_RSHIFT; case SC_LCONTROL: return VK_LCONTROL; case SC_RCONTROL: return VK_RCONTROL; case SC_LALT: return VK_LMENU; case SC_RALT: return VK_RMENU; // Numpad keys require explicit mapping because MapVirtualKey() doesn't support them on all OSes. // See comments in vk_to_sc() for details. case SC_NUMLOCK: return VK_NUMLOCK; case SC_NUMPADDIV: return VK_DIVIDE; case SC_NUMPADMULT: return VK_MULTIPLY; case SC_NUMPADSUB: return VK_SUBTRACT; case SC_NUMPADADD: return VK_ADD; case SC_NUMPADENTER: return VK_RETURN; // The following are ambiguous because each maps to more than one VK. But be careful // changing the value to the other choice because some callers rely upon the values // assigned below to determine which keys should be handled by scan code rather than vk: case SC_NUMPADDEL: return VK_DELETE; case SC_NUMPADCLEAR: return VK_CLEAR; case SC_NUMPADINS: return VK_INSERT; case SC_NUMPADUP: return VK_UP; case SC_NUMPADDOWN: return VK_DOWN; case SC_NUMPADLEFT: return VK_LEFT; case SC_NUMPADRIGHT: return VK_RIGHT; case SC_NUMPADHOME: return VK_HOME; case SC_NUMPADEND: return VK_END; case SC_NUMPADPGUP: return VK_PRIOR; case SC_NUMPADPGDN: return VK_NEXT; // No callers currently need the following alternate virtual key mappings. If it is ever needed, // could have a new aReturnSecondary parameter that if true, causes these to be returned rather // than the above: //case SC_NUMPADDEL: return VK_DECIMAL; //case SC_NUMPADCLEAR: return VK_NUMPAD5; // Same key as Numpad5 on most keyboards? //case SC_NUMPADINS: return VK_NUMPAD0; //case SC_NUMPADUP: return VK_NUMPAD8; //case SC_NUMPADDOWN: return VK_NUMPAD2; //case SC_NUMPADLEFT: return VK_NUMPAD4; //case SC_NUMPADRIGHT: return VK_NUMPAD6; //case SC_NUMPADHOME: return VK_NUMPAD7; //case SC_NUMPADEND: return VK_NUMPAD1; //case SC_NUMPADPGUP: return VK_NUMPAD9; //case SC_NUMPADPGDN: return VK_NUMPAD3; } // Use the OS API call to resolve any not manually set above. This should correctly // resolve even elements such as SC_INSERT, which is an extended scan code, because // it passes in only the low-order byte which is SC_NUMPADINS. In the case of SC_INSERT // and similar ones, MapVirtualKey() will return the same vk for both, which is correct. // Only pass the LOBYTE because I think it fails to work properly otherwise. // Also, DO NOT pass 3 for the 2nd param of MapVirtualKey() because apparently // that is not compatible with Win9x so it winds up returning zero for keys // such as UP, LEFT, HOME, and PGUP (maybe other sorts of keys too). This // should be okay even on XP because the left/right specific keys have already // been resolved above so don't need to be looked up here (LWIN and RWIN // each have their own VK's so shouldn't be problem for the below call to resolve): - return MapVirtualKey((BYTE)aSC, 1); + return MapVirtualKey(LOBYTE(aSC), 1); } diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip index 9a4be7f..40a0a81 100644 Binary files a/source/resources/WINAPI.zip and b/source/resources/WINAPI.zip differ diff --git a/source/script.cpp b/source/script.cpp index 5a41f99..0118def 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -9688,1078 +9688,1090 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic) : item_end; // It's the terminator, so let the loop detect that to finish. } if (buf_used) { // Above wrote at least one initializer expression into buf. buf[buf_used -= 2] = '\0'; // Remove the final ", " // The following section temporarily replaces mLastLine in order to insert script lines // either at the end of the list of static initializers (separate from the main script) // or at the end of the __Init method belonging to this class. Save the current values: Line *script_first_line = mFirstLine, *script_last_line = mLastLine; Line *block_end; Func *init_func = NULL; if (aStatic) { mLastLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } else { ExprTokenType token; if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT && (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability. { // __Init method already exists, so find the end of its body. for (block_end = init_func->mJumpToLine; block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute; block_end = block_end->mNextLine); } else { // Create an __Init method for this class. TCHAR def[] = _T("__Init()"); if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN) || (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation. return FAIL; mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out. init_func = g->CurrentFunc; init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions. if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL. return FAIL; block_end = mLastLine; block_end->mLineNumber = 0; // See above. // These must be updated as one or both have changed: script_first_line = mFirstLine; script_last_line = mLastLine; } g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this. mLastLine = block_end->mPrevLine; // i.e. insert before block_end. mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless. mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state. } if (!ParseAndAddLine(buf, ACT_EXPRESSION)) return FAIL; // Above already displayed the error. if (aStatic) { if (!mFirstStaticLine) mFirstStaticLine = mLastLine; mLastStaticLine = mLastLine; // The following is necessary if there weren't any executable lines above this static // initializer (i.e. mFirstLine was NULL and has been set to the newly created line): mFirstLine = script_first_line; } else { if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class. init_func->mJumpToLine = mLastLine; // Rejoin the function's block-end (and any lines following it) to the main script. mLastLine->mNextLine = block_end; block_end->mPrevLine = mLastLine; // mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our // __init function's block-begin, which is now the very first executable line in the script. g->CurrentFunc = NULL; } // Restore mLastLine so that any subsequent script lines are added at the correct point. mLastLine = script_last_line; } return OK; } Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength) { if (!aClassNameLength) aClassNameLength = _tcslen(aClassName); if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH) return NULL; LPTSTR cp, key; ExprTokenType token; Object *base_object = NULL; TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing. // Make temporary copy which we can modify. tmemcpy(class_name, aClassName, aClassNameLength); class_name[aClassNameLength] = '.'; // To simplify parsing. class_name[aClassNameLength + 1] = '\0'; // Get base variable; e.g. "MyClass" in "MyClass.MySubClass". cp = _tcschr(class_name + 1, '.'); Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL); if (!base_var) return NULL; // Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time: if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) ) return NULL; // Even if the loop below has no iterations, it initializes 'key' to the appropriate value: for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2. { if (cp == key) return NULL; // ScriptError(_T("Missing name."), cp); *cp = '\0'; // Terminate at the delimiting dot. if (!base_object->GetItem(token, key)) return NULL; base_object = (Object *)token.object; // See comment about Object() above. } return base_object; } Object *Object::GetUnresolvedClass(LPTSTR &aName) // This method is only valid for mUnresolvedClass. { if (!mFieldCount) return NULL; aName = mFields[0].key.s; return (Object *)mFields[0].object; } ResultType Script::ResolveClasses() { LPTSTR name; Object *base = mUnresolvedClasses->GetUnresolvedClass(name); if (!base) return OK; // There is at least one unresolved class. ExprTokenType token; if (base->GetItem(token, _T("__Class"))) { // In this case (an object in the mUnresolvedClasses list), it is always an integer // containing the file index and line number: mCurrFileIndex = int(token.value_int64 >> 32); mCombinedLineNumber = LineNumberType(token.value_int64); } mCurrLine = NULL; return ScriptError(_T("Unknown class."), name); } #ifndef AUTOHOTKEYSC struct FuncLibrary { LPTSTR path; DWORD_PTR length; }; Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude) // Caller must ensure that aFuncName doesn't already exist as a defined function. // If aFuncNameLength is 0, the entire length of aFuncName is used. { aErrorWasShown = false; // Set default for this output parameter. aFileWasFound = false; int i; LPTSTR char_after_last_backslash, terminate_here; TCHAR buf[MAX_PATH+1]; DWORD attr; TextMem tmem; TextMem::Buffer textbuf(NULL, 0, false); #define FUNC_LIB_EXT _T(".ahk") #define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1) #define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash. #define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1) #define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash. #define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1) #define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash. #define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1) #define FUNC_LIB_COUNT 4 static FuncLibrary sLib[FUNC_LIB_COUNT] = {0}; static LPTSTR winapi; if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance. { LPVOID aDataBuf; HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10)); DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd); #ifdef _UNICODE winapi = UTF8ToWide((LPCSTR)aDataBuf); #else winapi = (LPTSTR)aDataBuf; #endif for (i = 0; i < FUNC_LIB_COUNT; ++i) #ifdef _USRDLL if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst #else if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name. #endif return NULL; // Due to rarity, simply pass the failure back to caller. FuncLibrary *this_lib; // DETERMINE PATH TO "LOCAL" LIBRARY: this_lib = sLib; // For convenience and maintainability. this_lib->length = BIV_ScriptDir(NULL, _T("")); if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH) { this_lib->length = BIV_ScriptDir(this_lib->path, _T("")); _tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB); this_lib->length += FUNC_LOCAL_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "USER" LIBRARY: this_lib++; // For convenience and maintainability. this_lib->length = BIV_MyDocuments(this_lib->path, _T("")); if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB); this_lib->length += FUNC_USER_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "STANDARD" LIBRARY: this_lib++; // For convenience and maintainability. GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe. char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked. this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash. if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB); this_lib->length += FUNC_STD_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY: this_lib++; // For convenience and maintainability. BIV_AhkPath(this_lib->path, _T("")); _tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk")); *(_tcsrchr(this_lib->path,'\\')+8) = '\0'; CoInitialize(NULL); IShellLink *psl; if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) { #ifdef UNICODE if (SUCCEEDED(ppf->Load(this_lib->path, 0))) #else WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed. ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes. if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0))) #endif { TCHAR buf[MAX_PATH+1]; psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY); _tcscpy(this_lib->path,buf); _tcscpy(this_lib->path + _tcslen(buf),_T("\\\0")); } ppf->Release(); } psl->Release(); } CoUninitialize(); if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') ) { this_lib->length = 0; *this_lib->path = '\0'; } else this_lib->length = _tcslen(this_lib->path); for (i = 0; i < FUNC_LIB_COUNT; ++i) { attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code. if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order. { *sLib[i].path = '\0'; // Mark this library as disabled. sLib[i].length = 0; // } } } // Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library"). if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1]; LPTSTR naked_filename = aFuncName; // Set up for the first iteration. size_t naked_filename_length = aFuncNameLength; // for (int second_iteration = 0; second_iteration < 2; ++second_iteration) { for (i = 0; i < FUNC_LIB_COUNT; ++i) { if (!*sLib[i].path) // Library is marked disabled, so skip it. continue; if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH) continue; // Path too long to match in this library, but try others. dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path. _tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension. attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern. if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order. continue; aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found. // Since above didn't "continue", a file exists whose name matches that of the requested function. // Before loading/including that file, set the working directory to its folder so that if it uses // #Include, it will be able to use more convenient/intuitive relative paths. This is similar to // the "#Include DirName" feature. // Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like // C: that lacks a backslash (see SetWorkingDir() for details). terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library. *terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir(). SetWorkingDir(sLib[i].path); // See similar section in the #Include directive. *terminate_here = '\\'; // Undo the termination. if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude) { // For each auto-included library-file, write out two #Include lines: // 1) Use #Include in its "change working directory" mode so that any explicit #include directives // or FileInstalls inside the library file itself will work consistently and properly. // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include // the library file itself. // We don't directly append library files onto the main script here because: // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files // might contain #Include even though it's rare). // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file // and deposited separately/synchronously into the temp-include file by some new logic at the // AutoHotkey.exe's code for the #Include directive. // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts. mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n") , sLib[i].length, sLib[i].path, sLib[i].path); // Now continue on normally so that our caller can continue looking for syntax errors. } // g->CurrentFunc is non-NULL when the function-call being resolved is inside // a function. Save and reset it for correct behaviour in the include file: Func *current_func = g->CurrentFunc; g->CurrentFunc = NULL; // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { g->CurrentFunc = current_func; // Restore. aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } g->CurrentFunc = current_func; // Restore. // Now that a matching filename has been found, it seems best to stop searching here even if that // file doesn't actually contain the requested function. This helps library authors catch bugs/typos. // HotKeyIt, override so resource can be tried too if (current_func = FindFunc(aFuncName, aFuncNameLength)) return current_func; continue; } // for() each library directory. // Now that the first iteration is done, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. break; // All loops are done because second iteration is the last possible attempt. naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). break; // All loops are done because second iteration is the last possible attempt. naked_filename = class_name_buf; // Point it to a buffer for use below. tmemcpy(naked_filename, aFuncName, naked_filename_length); naked_filename[naked_filename_length] = '\0'; } // 2-iteration for(). // HotKeyIt find library in Resource // Since above didn't return, no match found in any library. // Search in Resource for a library // // If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource // If nothing in dll resource is found, search again in main executable. tmemcpy(class_name_buf, aFuncName, aFuncNameLength); tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4); class_name_buf[aFuncNameLength + 4] = '\0'; HRSRC lib_hResource; BOOL aUseHinstance = true; if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) { // Now that the resource is not found, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. aUseHinstance = false; if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) ) { if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. goto winapi; else { naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). return NULL; tmemcpy(class_name_buf, aFuncName, naked_filename_length); tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4); class_name_buf[naked_filename_length + 4] = '\0'; if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) ) { if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) ) goto winapi; } else aUseHinstance = true; } } } // Now a resouce was found and it can be loaded HGLOBAL hResData; HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL; if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource)) && (hResData = LoadResource(ahInstance, lib_hResource)) && (textbuf.mBuffer = LockResource(hResData)) ) ) { // aErrorWasShown = true; // Do not display errors here goto winapi; } if (*(unsigned int*)textbuf.mBuffer == 0x04034b50) { LPVOID aDataBuf; DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf); if (aSizeDeCompressed) { LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns memmove(buff,aDataBuf,aSizeDeCompressed); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); textbuf.mLength = aSizeDeCompressed; textbuf.mBuffer = buff; } } aFileWasFound = true; // NOTE: Ahk2Exe strips off the UTF-8 BOM. LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR)); tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8); tmem.Read(resource_script, textbuf.mLength); // g->CurrentFunc is non-NULL when the function-call being resolved is inside // a function. Save and reset it for correct behaviour in the include file: Func *current_func = g->CurrentFunc; g->CurrentFunc = NULL; // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { g->CurrentFunc = current_func; // Restore. aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } g->CurrentFunc = current_func; // Restore. return FindFunc(aFuncName, aFuncNameLength); winapi: TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' }; memmove(&parameter[11], aFuncName, aFuncNameLength*sizeof(TCHAR)); parameter[aFuncNameLength + 11] = L','; parameter[aFuncNameLength + 12] = '\0'; LPTSTR found; if (found = _tcsstr(winapi, (LPTSTR)&parameter[10])) { parameter[10] = L','; LPTSTR aDest = (LPTSTR)&parameter[aFuncNameLength + 12]; LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1; size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1; _tcsncpy(aDest, aDllName, aNameLen); aDest = aDest + aNameLen; _tcsncpy(aDest, found + 1, aFuncNameLength + 1); - aDest = aDest + aFuncNameLength + 1; + // Override _ in the end of definition (ahk function like SendMessage, Sleep, Send, SendInput ... + if (*(aFuncName + aFuncNameLength - 1) == '_') + { + *(aDest + aFuncNameLength - 1) = ','; + *(aDest + aFuncNameLength) = '\0'; + aDest = aDest + aFuncNameLength; + } + else + { + aDest = aDest + aFuncNameLength + 1; + } for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++) { if (*found == L'U' || *found == L'u') { *aDest = L'U'; aDest++; continue; } if (*found == L's' || *found == L'S') { _tcscpy(aDest, _T("STR")); aDest = aDest + 3; } else if (*found == L't' || *found == L't') { _tcscpy(aDest, _T("PTR")); aDest = aDest + 3; } else if (*found == L'a' || *found == L'A') { _tcscpy(aDest, _T("ASTR")); aDest = aDest + 4; } else if (*found == L'w' || *found == L'W') { _tcscpy(aDest, _T("WSTR")); aDest = aDest + 4; } else if (*found == L'x' || *found == L'X') //TCHAR { #ifdef _UNICODE _tcscpy(aDest, _T("USHORT")); aDest = aDest + 6; #else _tcscpy(aDest, _T("UCHAR")); aDest = aDest + 5; #endif } else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6') { _tcscpy(aDest, _T("INT64")); aDest = aDest + 5; found++; } else if (*found == L'i' || *found == L'I') { - if (*(found + 1) != L'\\') - { // Default Return type int, no need to define + if (*(found + 1) != L'\\' || *(aDest - 1) == 'u' || *(aDest - 1) == 'U') + { // Not default return type int, no need to define _tcscpy(aDest, _T("INT")); aDest = aDest + 3; } else // remove last , since no return type is given + { aDest--; + } } else if (*found == L'h' || *found == L'H') { _tcscpy(aDest, _T("SHORT")); aDest = aDest + 5; } else if (*found == L'c' || *found == L'C') { _tcscpy(aDest, _T("CHAR")); aDest = aDest + 4; } else if (*found == L'f' || *found == L'F') { _tcscpy(aDest, _T("FLOAT")); aDest = aDest + 5; } else if (*found == L'd' || *found == L'D') { _tcscpy(aDest, _T("DOUBLE")); aDest = aDest + 6; } if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P') { *aDest = *found; aDest++; } _tcscpy(aDest, _T(",,")); aDest = aDest + 2; } *(aDest - 2) = L'\0'; LoadDllFunction(_tcschr(parameter, L',') + 1, parameter); return FindFunc(aFuncName, aFuncNameLength); } return NULL; } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } else if (!_tcsicmp(func_name, _T("Struct"))) { bif = BIF_Struct; min_params = 1; max_params = 3; } else if (!_tcsicmp(func_name, _T("Sizeof"))) { bif = BIF_sizeof; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9. { bif = BIF_UnZipRawMemory; min_params = 1; max_params = 3; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } else if (!_tcsicmp(func_name, _T("StrSplit"))) { bif = BIF_StrSplit; min_params = 1; max_params = 3; } else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; } else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 5; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryFindResource"))) { bif = BIF_MemoryFindResource; min_params = 3; max_params = 4; } else if (!_tcsicmp(func_name, _T("MemorySizeOfResource"))) { bif = BIF_MemorySizeOfResource; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryLoadResource"))) { bif = BIF_MemoryLoadResource; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryLoadString"))) { bif = BIF_MemoryLoadString; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1.
tinku99/ahkdll
96500b251333afd17e7f77751c84f98197aa48e0
Fix ahkdll did not return when load error occured
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 3149f8c..53e6e60 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -15,1043 +15,1042 @@ GNU General Public License for more details. */ #include "stdafx.h" // pre-compiled headers #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (scriptstring) free(scriptstring); if (Line::sMaxSourceFiles) free(Line::sSourceFile); #ifdef _DEBUG free(g_Debugger.mStack.mBottom); #endif #ifndef MINIDLL if (g_input.MatchCount) { free(g_input.match); } if (g_script.mTrayMenu) g_script.ScriptDeleteMenu(g_script.mTrayMenu); free(g_KeyHistory); #endif break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { OleInitialize(NULL); - OldWinMain(nameHinstanceP.hInstanceP, 0, nameHinstanceP.name, 0); + int result = OldWinMain(nameHinstanceP.hInstanceP, 0, nameHinstanceP.name, 0); g_script.Destroy(); - CloseHandle(hThread); - hThread = NULL; - _endthreadex( (DWORD)EARLY_RETURN ); + _endthreadex( result); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { + CloseHandle(hThread); hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed Sleep(50); int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, NULL, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); HANDLE oldhThread = hThread; hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; CloseHandle(oldhThread); _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; CloseHandle(hThread); hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute || g_Reloading || g_Loading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) { if (IsUnicode==NULL) return ERROR_INVALID_PARAMETER; *IsUnicode = com_ahkIsUnicode(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) { // search for TypeLib in current dll WCHAR buf[MAX_PATH * sizeof(WCHAR)]; // LoadTypeLibEx needs Unicode string if (GetModuleFileNameW(g_hInstance, buf, _countof(buf))) hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); else // MemoryModule, search troug g_ListOfMemoryModules and use temp file to extract and load TypeLib file { HMEMORYMODULE hmodule = (HMEMORYMODULE)(g_hMemoryModule); HMEMORYRSRC res = MemoryFindResource(hmodule,_T("TYPELIB"),MAKEINTRESOURCE(1)); if (!res) return TYPE_E_INVALIDSTATE; DWORD resSize = MemorySizeOfResource(hmodule,res); // Path to temp directory + our temporary file name DWORD tempPathLength = GetTempPathW(MAX_PATH, buf); wcscpy(buf + tempPathLength,L"AutoHotkey.MemoryModule.temp.tlb"); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after LoadTypeLib has been called. HANDLE hFile = CreateFileW(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,MemoryLoadResource(hmodule,res),resSize,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to write data, continue and try loading } hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileW(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); } if (FAILED(hr)) return hr; } // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; }
tinku99/ahkdll
3bdd9ea32e9b98ec27af7bf196d46bf2b147a189
Use SimpleHeap for #DllImport
diff --git a/source/util.cpp b/source/util.cpp index 84a5b16..acc8354 100644 --- a/source/util.cpp +++ b/source/util.cpp @@ -2335,819 +2335,819 @@ HICON ExtractIconFromExecutable(LPTSTR aFilespec, int aIconNumber, int aWidth, i HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon) // Converts HICON to an HBITMAP that has ahIcon's actual dimensions. // The incoming ahIcon will be destroyed if the caller passes true for aDestroyIcon. // Returns NULL on failure, in which case aDestroyIcon will still have taken effect. // If the icon contains any transparent pixels, they will be mapped to CLR_NONE within // the bitmap so that the caller can detect them. { if (!ahIcon) return NULL; HBITMAP hbitmap = NULL; // Set default. This will be the value returned. HDC hdc_desktop = GetDC(HWND_DESKTOP); HDC hdc = CreateCompatibleDC(hdc_desktop); // Don't pass NULL since I think that would result in a monochrome bitmap. if (hdc) { ICONINFO ii; if (GetIconInfo(ahIcon, &ii)) { BITMAP icon_bitmap; // Find out how big the icon is and create a bitmap compatible with the desktop DC (not the memory DC, // since its bits per pixel (color depth) is probably 1. if (GetObject(ii.hbmColor, sizeof(BITMAP), &icon_bitmap) && (hbitmap = CreateCompatibleBitmap(hdc_desktop, icon_bitmap.bmWidth, icon_bitmap.bmHeight))) // Assign { // To retain maximum quality in case caller needs to resize the bitmap we return, convert the // icon to a bitmap that matches the icon's actual size: HGDIOBJ old_object = SelectObject(hdc, hbitmap); if (old_object) // Above succeeded. { // Use DrawIconEx() vs. DrawIcon() because someone said DrawIcon() always draws 32x32 // regardless of the icon's actual size. // If it's ever needed, this can be extended so that the caller can pass in a background // color to use in place of any transparent pixels within the icon (apparently, DrawIconEx() // skips over transparent pixels in the icon when drawing to the DC and its bitmap): RECT rect = {0, 0, icon_bitmap.bmWidth, icon_bitmap.bmHeight}; // Left, top, right, bottom. HBRUSH hbrush = CreateSolidBrush(CLR_DEFAULT); FillRect(hdc, &rect, hbrush); DeleteObject(hbrush); // Probably something tried and abandoned: FillRect(hdc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH)); DrawIconEx(hdc, 0, 0, ahIcon, icon_bitmap.bmWidth, icon_bitmap.bmHeight, 0, NULL, DI_NORMAL); // Debug: Find out properties of new bitmap. //BITMAP b; //GetObject(hbitmap, sizeof(BITMAP), &b); SelectObject(hdc, old_object); // Might be needed (prior to deleting hdc) to prevent memory leak. } } // It's our responsibility to delete these two when they're no longer needed: DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DeleteDC(hdc); } ReleaseDC(HWND_DESKTOP, hdc_desktop); if (aDestroyIcon) DestroyIcon(ahIcon); return hbitmap; } // Lexikos: Used for menu icons on Windows Vista and later. Some similarities to IconToBitmap, maybe should be merged if IconToBitmap does not specifically need to create a device-dependent bitmap? HBITMAP IconToBitmap32(HICON ahIcon, bool aDestroyIcon) { // Get the icon's internal colour and mask bitmaps. // hbmColor is needed to measure the icon. // hbmMask is needed to generate an alpha channel if the icon does not have one. ICONINFO icon_info; if (!GetIconInfo(ahIcon, &icon_info)) return NULL; HBITMAP hbitmap = NULL; // Set default in case of failure. // Get size of icon's internal bitmap. BITMAP icon_bitmap; if (GetObject(icon_info.hbmColor, sizeof(BITMAP), &icon_bitmap)) { int width = icon_bitmap.bmWidth; int height = icon_bitmap.bmHeight; HDC hdc = CreateCompatibleDC(NULL); if (hdc) { BITMAPINFO bitmap_info = {0}; // Set parameters for 32-bit bitmap. May also be used to retrieve bitmap data from the icon's mask bitmap. BITMAPINFOHEADER &bitmap_header = bitmap_info.bmiHeader; bitmap_header.biSize = sizeof(BITMAPINFOHEADER); bitmap_header.biWidth = width; bitmap_header.biHeight = height; bitmap_header.biBitCount = 32; bitmap_header.biPlanes = 1; // Create device-independent bitmap. UINT *bits; if (hbitmap = CreateDIBSection(hdc, &bitmap_info, 0, (void**)&bits, NULL, 0)) { HGDIOBJ old_object = SelectObject(hdc, hbitmap); if (old_object) // Above succeeded. { // Draw icon onto bitmap. Use DrawIconEx because DrawIcon always draws a large (usually 32x32) icon! DrawIconEx(hdc, 0, 0, ahIcon, 0, 0, 0, NULL, DI_NORMAL); // May be necessary for bits to be in sync, according to documentation for CreateDIBSection: GdiFlush(); // Calculate end of bitmap data. UINT *bits_end = bits + width*height; UINT *this_pixel; // Used in a few loops below. // Check for alpha data. bool has_nonzero_alpha = false; for (this_pixel = bits; this_pixel < bits_end; ++this_pixel) { if (*this_pixel >> 24) { has_nonzero_alpha = true; break; } } if (!has_nonzero_alpha) { // Get bitmap data from the icon's mask. UINT *mask_bits = (UINT*)_alloca(height*width*4); if (GetDIBits(hdc, icon_info.hbmMask, 0, height, (LPVOID)mask_bits, &bitmap_info, 0)) { UINT *this_mask_pixel; // Use the icon's mask to generate alpha data. for (this_pixel = bits, this_mask_pixel = mask_bits; this_pixel < bits_end; ++this_pixel, ++this_mask_pixel) { if (*this_mask_pixel) *this_pixel = 0; else *this_pixel |= 0xff000000; } } else { // GetDIBits failed, simply make the bitmap opaque. for (this_pixel = bits; this_pixel < bits_end; ++this_pixel) *this_pixel |= 0xff000000; } } SelectObject(hdc, old_object); } else { // Probably very rare, but be on the safe side. DeleteObject(hbitmap); hbitmap = NULL; } } DWORD dwError = GetLastError(); DeleteDC(hdc); } } // It's our responsibility to delete these two when they're no longer needed: DeleteObject(icon_info.hbmColor); DeleteObject(icon_info.hbmMask); if (aDestroyIcon) DestroyIcon(ahIcon); return hbitmap; } HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList) { // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP. // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally // in case older OSes can ever have it. HRESULT hresult = !S_OK; // Set default as "failure". HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme")); if (hinstTheme) { typedef HRESULT (WINAPI *MySetWindowThemeType)(HWND, LPCWSTR, LPCWSTR); MySetWindowThemeType DynSetWindowTheme = (MySetWindowThemeType)GetProcAddress(hinstTheme, "SetWindowTheme"); if (DynSetWindowTheme) hresult = DynSetWindowTheme(hwnd, pszSubAppName, pszSubIdList); FreeLibrary(hinstTheme); } return hresult; } //HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags) //{ // // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP. // // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally // // in case older OSes can ever have it. // HRESULT hresult = !S_OK; // Set default as "failure". // HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme")); // if (hinstTheme) // { // typedef HRESULT (WINAPI *MyEnableThemeDialogTextureType)(HWND, DWORD); // MyEnableThemeDialogTextureType DynEnableThemeDialogTexture = (MyEnableThemeDialogTextureType)GetProcAddress(hinstTheme, "EnableThemeDialogTexture"); // if (DynEnableThemeDialogTexture) // hresult = DynEnableThemeDialogTexture(hwnd, dwFlags); // FreeLibrary(hinstTheme); // } // return hresult; //} LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace) // Replaces any escape sequences in aBuf with their reduced equivalent. For example, if aEscapeChar // is accent, Each `n would become a literal linefeed. aBuf's length should always be the same or // lower than when the process started, so there is no chance of overflow. { LPTSTR cp, cp1; for (cp = aBuf; ; ++cp) // Increment to skip over the symbol just found by the inner for(). { for (; *cp && *cp != aEscapeChar; ++cp); // Find the next escape char. if (!*cp) // end of string. break; cp1 = cp + 1; switch (*cp1) { // Only lowercase is recognized for these: case 'a': *cp1 = '\a'; break; // alert (bell) character case 'b': *cp1 = '\b'; break; // backspace case 'f': *cp1 = '\f'; break; // formfeed case 'n': *cp1 = '\n'; break; // newline case 'r': *cp1 = '\r'; break; // carriage return case 't': *cp1 = '\t'; break; // horizontal tab case 'v': *cp1 = '\v'; break; // vertical tab case 's': // space (not always allowed for backward compatibility reasons). if (aAllowEscapedSpace) *cp1 = ' '; //else do nothing extra, just let the standard action for unrecognized escape sequences. break; // Otherwise, if it's not one of the above, the escape-char is considered to // mark the next character as literal, regardless of what it is. Examples: // `` -> ` // `:: -> :: (effectively) // `; -> ; // `c -> c (i.e. unknown escape sequences resolve to the char after the `) } // Below has a final +1 to include the terminator: tmemmove(cp, cp1, _tcslen(cp1) + 1); } return aBuf; } int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter, int aStartIndex, LPCTSTR aLiteralMap) // Returns the index of the next delimiter, taking into account quotes, parentheses, etc. // If the delimiter is not found, returns the length of aBuf. { bool in_quotes = false; int open_parens = 0; for (int mark = aStartIndex; ; ++mark) { if (aBuf[mark] == aDelimiter) { if (!in_quotes && open_parens <= 0 && !(aLiteralMap && aLiteralMap[mark])) // A delimiting comma other than one in a sub-statement or function. return mark; // Otherwise, its a quoted/literal comma or one in parentheses (such as function-call). continue; } switch (aBuf[mark]) { case '"': // There are sections similar this one later below; so see them for comments. in_quotes = !in_quotes; break; case '(': // For our purpose, "(", "[" and "{" can be treated the same. case '[': // If they aren't balanced properly, a later stage will detect it. case '{': // if (!in_quotes) // Literal parentheses inside a quoted string should not be counted for this purpose. ++open_parens; break; case ')': case ']': case '}': if (!in_quotes) --open_parens; // If this makes it negative, validation later on will catch the syntax error. break; case '\0': // Reached the end of the string without finding a delimiter. Return the // index of the null-terminator since that's typically what the caller wants. return mark; //default: some other character; just have the loop skip over it. } } } bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch) // Checks if aStr exists in aList (which is a comma-separated list). // If aStr is blank, aList must start with a delimiting comma for there to be a match. { // Must use a temp. buffer because otherwise there's no easy way to properly match upon strings // such as the following: // if var in string,,with,,literal,,commas TCHAR buf[LINE_SIZE]; TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1; // v1.0.48.01: Performance improved by Lexikos. for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList. { for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer. { if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,). { ++next_field; if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field. break; // Otherwise it's ",," and next_field now points at the second comma; so copy that comma // over as a literal comma then continue copying. } *cp = *next_field; } // The end of this field has been reached (or reached the capacity of the buffer), so terminate the string // in the buffer. *cp = '\0'; if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc { if (aFindExactMatch) { if (!g_tcscmp(aStr, buf)) // Match found return true; } else // Substring match if (g_tcsstr(aStr, buf)) // Match found return true; } else // First item in the list is the empty string. if (aFindExactMatch) // In this case, this is a match if aStr is also blank. { if (!*aStr) return true; } else // Empty string is always found as a substring in any other string. return true; } // for() return false; // No match found. } LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen) { // For each character in aStr: for ( ; *aStr; ++aStr) // For each needle: for (int i = 0; i < aNeedleCount; ++i) // For each character in this needle: for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos) { if (!*needle_pos) { // All characters in needle matched aStr at this position, so we've // found our string. If this needle is empty, it implicitly matches // at the first position in the string. aFoundLen = needle_pos - aNeedle[i]; return aStr; } // Otherwise, we haven't reached the end of the needle. If we've reached // the end of aStr, *str_pos and *needle_pos won't match, so the check // below will break out of the loop. if (*needle_pos != *str_pos) // Not a match: continue on to the next needle, or the next starting // position in aStr if this is the last needle. break; } // If the above loops completed without returning, no matches were found. return NULL; } short IsDefaultType(LPTSTR aTypeDef){ static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ") #ifndef _WIN64 ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ") #else ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ") #endif ,_T("") #ifdef _WIN64 ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ") #else ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #endif ,_T(""),_T(""),_T("") #ifdef _WIN64 ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #else ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ") #endif }; for (int i=0;i<8;i++) { if (tcscasestr(sTypeDef[i],aTypeDef)) return i + 1; } // type was not found return NULL; } ResultType LoadDllFunction(LPTSTR parameter, LPTSTR aBuf) { LPTSTR aFuncName = omit_leading_whitespace(parameter); // backup current function // Func currentfunc = **g_script.mFunc; if (!(parameter = _tcschr(parameter, ',')) || !*parameter) return g_script.ScriptError(ERR_PARAM2_REQUIRED, aBuf); else parameter++; if (_tcschr(aFuncName, ',')) *(_tcschr(aFuncName, ',')) = '\0'; ltrim(parameter); int insert_pos; Func *found_func = g_script.FindFunc(aFuncName, _tcslen(aFuncName), &insert_pos); if (found_func) return g_script.ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined." else if (!(found_func = g_script.AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos))) return FAIL; // It already displayed the error. void *function = NULL; // Will hold the address of the function to be called. found_func->mBIF = (BuiltInFunctionType)BIF_DllImport; found_func->mIsBuiltIn = true; found_func->mMinParams = 0; TCHAR buf[MAX_PATH]; size_t space_remaining = LINE_SIZE - (parameter - aBuf); if (tcscasestr(parameter, _T("%A_ScriptDir%"))) { BIV_ScriptDir(buf, _T("A_ScriptDir")); StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis. { BIV_SpecialFolderPath(buf, _T("A_AppData")); StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04. { BIV_SpecialFolderPath(buf, _T("A_AppDataCommon")); StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04. { BIV_AhkPath(buf, _T("A_AhkPath")); StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkDir%"))) // v1.0.45.04. { BIV_AhkDir(buf, _T("A_AhkDir")); StrReplace(parameter, _T("%A_AhkDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllDir%"))) // v1.0.45.04. { BIV_DllDir(buf, _T("A_DllDir")); StrReplace(parameter, _T("%A_DllDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04. { BIV_DllPath(buf, _T("A_DllPath")); StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (_tcschr(parameter, '%')) { return g_script.ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_AhkDir% %A_DllPath% %A_DllDir% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter); } // terminate dll\function name, find it and jump to next parameter if (_tcschr(parameter, ',')) *(_tcschr(parameter, ',')) = '\0'; function = (void*)ATOI64(parameter); if (!function) { LPTSTR dll_name = _tcsrchr(parameter, '\\'); if (dll_name) { *dll_name = '\0'; if (!GetModuleHandle(parameter)) LoadLibrary(parameter); *dll_name = '\\'; } function = (void*)GetDllProcAddress(parameter); } if (!function) return g_script.ScriptError(ERR_NONEXISTENT_FUNCTION, parameter); parameter = parameter + _tcslen(parameter) + 1; LPTSTR parm = SimpleHeap::Malloc(parameter); bool has_return = false; int aParamCount = ATOI(parm) ? 0 : 1; if (*parm) for (; _tcschr(parameter, ','); aParamCount++) { if (parameter = _tcschr(parameter, ',')) parameter++; } if (*parm && aParamCount < 1) return g_script.ScriptError(ERR_PARAM3_REQUIRED, aBuf); // Determine the type of return value. - DYNAPARM *return_attrib = (DYNAPARM*)malloc(sizeof(DYNAPARM)); + DYNAPARM *return_attrib = (DYNAPARM*)SimpleHeap::Malloc(sizeof(DYNAPARM)); memset(return_attrib, 0, sizeof(DYNAPARM)); // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (!(aParamCount % 2)) // Even number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib->type = DLL_ARG_INT; else { // Check validity of this arg's return type: LPTSTR return_type_string[2]; return_type_string[0] = parameter; return_type_string[1] = NULL; // Added in 1.0.48. // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } ConvertDllArgType(return_type_string, *return_attrib); if (return_attrib->type == DLL_ARG_INVALID) return CONDITION_FALSE; has_return = true; has_valid_return_type: aParamCount--; #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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount / 2; // Might provide one extra due to first/last params, which is inconsequential. - DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)malloc(arg_count * sizeof(DYNAPARM)) : NULL; - DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)malloc(arg_count * sizeof(DYNAPARM)) : NULL; + DYNAPARM *dyna_param_def = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(arg_count * sizeof(DYNAPARM)) : NULL; + DYNAPARM *dyna_param = arg_count ? (DYNAPARM *)SimpleHeap::Malloc(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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif - malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases. + SimpleHeap::Malloc(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. LPTSTR this_param; for (arg_count = 0, i = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { this_param = _tcschr(parm, ','); *this_param = '\0'; this_param++; arg_type_string[0] = parm; // It will be detected as invalid below. arg_type_string[1] = NULL; //ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param_def[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (ATOI64(this_param)) { // 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. return CONDITION_FALSE; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = 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 forget to call VarSetCapacity before passing a buffer 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 (ATOI64(this_param)) return CONDITION_FALSE; // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar, CStringWCharFromChar)(this_param); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. this_dyna_param.value_double = ATOF(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_INVALID: return CONDITION_FALSE; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !ATOI64(this_param)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(this_param); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ATOI64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) parm = _tcschr(this_param,',') + 1; } // for() each arg. if (has_return) *(this_param) = '\0'; found_func->mClass = (Object*)function; found_func->mParamCount = arg_count; found_func->mVar = (Var**)return_attrib; found_func->mStaticVar = (Var**)pStr; found_func->mLazyVar = (Var**)dyna_param_def; found_func->mParam = (FuncParam*)dyna_param; #ifdef WIN32_PLATFORM found_func->mVarCount = dll_call_mode; #endif return CONDITION_TRUE; } DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression { unsigned int hdrsz = 20; TCHAR pw[1024] = {0}; if (pwd && pwd[0]) for(unsigned int i = 0;pwd[i];i++) pw[i] = (TCHAR)*pwd[i]; ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8); DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16); DWORD hash; BYTE *aDataEncrypted = NULL; HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4); if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4)) { HUNZIP huz; ZIPENTRY ze; DWORD result; ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12); aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE); if (aDataBuf) { if (aSizeEncrypted) { typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*); HMODULE advapi32 = LoadLibrary(_T("advapi32.dll")); MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt"); LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE); DWORD aSizeEncryptedString = aSizeEncrypted; DWORD aSizeEncryptedTemp = aSizeEncrypted; HCRYPTPROV hProv; HCRYPTKEY hKey; HCRYPTHASH hHash; CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT); CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash); CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0); CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey); CryptDestroyHash(hHash); memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted); Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL); if (aSizeEncryptedTemp == 0) { // incorrect password VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL); VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE); CryptDestroyKey(hKey); CryptReleaseContext(hProv,0); if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } } else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); return 0; } ze.CompressedSize = aSizeDeCompressed; ze.UncompressedSize = aSizeDeCompressed; if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY))) VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); else { closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return aSizeDeCompressed; } closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); } } return 0; } #ifndef MINIDLL LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs) { // Disable all hooks to avoid system/mouse freeze if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && pExceptionPtrs->ExceptionRecord->ExceptionFlags == EXCEPTION_NONCONTINUABLE) AddRemoveHooks(0); return EXCEPTION_CONTINUE_SEARCH; } #endif #if defined(_MSC_VER) && defined(_DEBUG) void OutputDebugStringFormat(LPCTSTR fmt, ...) { CString sMsg; va_list ap; va_start(ap, fmt); sMsg.FormatV(fmt, ap); OutputDebugString(sMsg); } #endif
tinku99/ahkdll
dd71dde526a87be7911e52802a0d2be031b9f53a
Fixed a bug
diff --git a/source/script.cpp b/source/script.cpp index 11cfdb3..5a41f99 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,821 +1,825 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL), mClassProperty(NULL), mClassPropertyDef(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; #ifdef _USRDLL if (menu_to_delete != mTrayMenu) #endif ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #ifdef _USRDLL if (mFirstMenu != mTrayMenu) { mFirstMenu = NULL; mLastMenu = NULL; mTrayMenu = NULL; } - else + else if (mFirstMenu) { mFirstMenu->mNextMenu = NULL; mLastMenu = mFirstMenu; } #endif #endif // MINIDLL // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); // Unregister window class registered in Script::CreateWindows #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN, g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH, g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN, g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH, g_hInstance); #endif #endif // MINIDLL } if (g_hAccelTable) DestroyAcceleratorTable(g_hAccelTable); if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL RemoveVectoredExceptionHandler(g_ExceptionHandler); // Exception handler to remove hooks to avoid system/mouse freeze #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL +#ifndef _USRDLL + DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. + DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. +#endif OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // free Meta Object g_MetaObject.Free(); // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; for (v = 0; v < mVarCount; v++) { if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) mVar[v]->mObject->Release(); mVar[v]->ConvertToNonAliasIfNecessary(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; v++) { if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) mLazyVar[v]->mObject->Release(); mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; v++) { if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } for (v = 0; v < f.mVarCount; v++) { if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; v++) { if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } } // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience.
tinku99/ahkdll
067c3942991920edce21bb6aadc391b3fd9bae84
Fix crash on FreeLibrary
diff --git a/source/SimpleHeap.cpp b/source/SimpleHeap.cpp index 21a9f6c..5c0d76b 100644 --- a/source/SimpleHeap.cpp +++ b/source/SimpleHeap.cpp @@ -1,206 +1,207 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 "SimpleHeap.h" #include "globaldata.h" // for g_script, so that errors can be centrally reported here. // Static member data: SimpleHeap *SimpleHeap::sFirst = NULL; SimpleHeap *SimpleHeap::sLast = NULL; char *SimpleHeap::sMostRecentlyAllocated = NULL; UINT SimpleHeap::sBlockCount = 0; SimpleHeap **sBlocks; LPTSTR SimpleHeap::Malloc(LPTSTR aBuf, size_t aLength) // v1.0.44.14: Added aLength to improve performance in cases where callers already know the length. // If aLength is at its default of -1, the length will be calculated here. // Caller must ensure that aBuf isn't NULL. { if (!aBuf || !*aBuf) // aBuf is checked for NULL because it's not worth avoiding it for such a low-level, frequently-called function. return _T(""); // Return the constant empty string to the caller (not aBuf itself since that might be volatile). if (aLength == -1) // Caller wanted us to calculate it. Compare directly to -1 since aLength is unsigned. aLength = _tcslen(aBuf); LPTSTR new_buf; if (!(new_buf = (LPTSTR)SimpleHeap::Malloc((aLength + 1) * sizeof(TCHAR)))) // +1 for the zero terminator. { g_script.ScriptError(ERR_OUTOFMEM, aBuf); return NULL; // Callers may rely on NULL vs. "" being returned in the event of failure. } if (aLength) tmemcpy(new_buf, aBuf, aLength); // memcpy() typically benchmarks slightly faster than strcpy(). //else only a terminator is needed. new_buf[aLength] = '\0'; // Terminate here for when aLength==0 and for the memcpy above so that caller's aBuf doesn't have to be terminated. return new_buf; } void* SimpleHeap::Malloc(size_t aSize) // This could be made more memory efficient by searching old blocks for sufficient // free space to handle <size> prior to creating a new block. But the whole point // of this class is that it's only called to allocate relatively small objects, // such as the lines of text in a script file. The length of such lines is typically // around 80, and only rarely would exceed 1000. Trying to find memory in old blocks // seems like a bad trade-off compared to the performance impact of traversing a // potentially large linked list or maintaining and traversing an array of // "under-utilized" blocks. { if (aSize < 1 || aSize > BLOCK_SIZE) return NULL; if (!sFirst) // We need at least one block to do anything, so create it. if (!(sFirst = CreateBlock())) return NULL; if (aSize > sLast->mSpaceAvailable) if (!(sLast->mNextBlock = CreateBlock())) return NULL; sMostRecentlyAllocated = sLast->mFreeMarker; // THIS IS NOW THE NEWLY ALLOCATED BLOCK FOR THE CALLER, which is 32-bit aligned because the previous call to this function (i.e. the logic below) set it up that way. // v1.0.40.04: Set up the NEXT chunk to be aligned on a 32-bit boundary (the first chunk in each block // should always be aligned since the block's address came from malloc()). On average, this change // "wastes" only 1.5 bytes per chunk. In a 200 KB script of typical contents, this change requires less // than 8 KB of additional memory (as shown by temporarily making BLOCK_SIZE a smaller value such as 8 KB // for a more accurate measurement). That cost seems well worth the following benefits: // 1) Solves failure of API functions like GetRawInputDeviceList() when passed a non-aligned address. // 2) May solve other obscure issues (past and future), which improves sanity due to not chasing bugs // for hours on end that were caused solely by non-alignment. // 3) May slightly improve performance since aligned data is easier for the CPU to access and cache. size_t remainder = aSize % sizeof(void *); size_t size_consumed = remainder ? aSize + (sizeof(void *) - remainder) : aSize; // v1.0.45: The following can't happen when BLOCK_SIZE is a multiple of 4, so it's commented out: //if (size_consumed > sLast->mSpaceAvailable) // For maintainability, don't allow mFreeMarker to go out of bounds or // size_consumed = sLast->mSpaceAvailable; // mSpaceAvailable to go negative (which it can't due to be unsigned). sLast->mFreeMarker += size_consumed; sLast->mSpaceAvailable -= size_consumed; return (void *)sMostRecentlyAllocated; } void SimpleHeap::Delete(void *aPtr) // If aPtr is the most recently allocated area of memory by SimpleHeap, this will reclaim that // memory. Otherwise, the caller should realize that the memory cannot be reclaimed (i.e. potential // memory leak unless caller handles things right). { if (aPtr != sMostRecentlyAllocated || !sMostRecentlyAllocated) return; size_t sMostRecentlyAllocated_size = sLast->mFreeMarker - sMostRecentlyAllocated; sLast->mFreeMarker -= sMostRecentlyAllocated_size; sLast->mSpaceAvailable += sMostRecentlyAllocated_size; sMostRecentlyAllocated = NULL; // i.e. no support for anything other than a one-time delete of an item just added. } // Commented out because not currently used: void SimpleHeap::DeleteAll() // See Hotkey::AllDestructAndExit for comments about why this isn't actually called. { -#ifdef _USRDLL - EnterCriticalSection(&g_CriticalHeapBlocks); -#endif + // Do not EnterCriticalSection because the dll might be being deattached and critical section already deleted, see dllmain->DllMain. if (sBlocks) // don't process again if we already freed Heap { +#ifdef _USRDLL + EnterCriticalSection(&g_CriticalHeapBlocks); +#endif for (; sBlockCount;) { if (sBlocks[--sBlockCount]) delete sBlocks[sBlockCount]; sBlocks[sBlockCount] = NULL; } sFirst = NULL; sLast = NULL; sMostRecentlyAllocated = NULL; free(sBlocks); sBlocks = NULL; - } #ifdef _USRDLL - LeaveCriticalSection(&g_CriticalHeapBlocks); + LeaveCriticalSection(&g_CriticalHeapBlocks); #endif + } } SimpleHeap *SimpleHeap::CreateBlock() // Added for v1.0.40.04 to try to solve the fact that some functions such as GetRawInputDeviceList() // will sometimes fail if passed memory from SimpleHeap. Although this change didn't actually solve // the issue (it turned out to be a 32-bit alignment issue), using malloc() appears to save memory // (compared to using "new" on a class that contains a large buffer such as "char mBlock[BLOCK_SIZE]"). // In a 200 KB script, it saves 8 KB of VM Size as shown by Task Manager. { #ifdef _USRDLL EnterCriticalSection(&g_CriticalHeapBlocks); #endif SimpleHeap *block; if (!(block = new SimpleHeap)) { #ifdef _USRDLL LeaveCriticalSection(&g_CriticalHeapBlocks); #endif return NULL; } // The new block's mFreeMarker starts off pointing to the first byte in the new block: if (!(block->mBlock = block->mFreeMarker = (char *)malloc(BLOCK_SIZE))) { delete block; #ifdef _USRDLL LeaveCriticalSection(&g_CriticalHeapBlocks); #endif return NULL; } // Since above didn't return, block was successfully created: block->mSpaceAvailable = BLOCK_SIZE; sLast = block; // Constructing a new block always results in it becoming the current block. if (!sBlockCount || !(sBlockCount % 1024)) { SimpleHeap **new_Blocks; if (!(new_Blocks = (SimpleHeap**)realloc(sBlocks, (!sBlockCount ? 1024 : sBlockCount * 2) * sizeof(SimpleHeap*)))) { delete block; #ifdef _USRDLL LeaveCriticalSection(&g_CriticalHeapBlocks); #endif return NULL; } sBlocks = new_Blocks; } sBlocks[sBlockCount] = block; ++sBlockCount; #ifdef _USRDLL LeaveCriticalSection(&g_CriticalHeapBlocks); #endif return block; } SimpleHeap::SimpleHeap() // Construct a new block. Caller is responsible for initializing other members. : mNextBlock(NULL) { } SimpleHeap::~SimpleHeap() // This destructor is currently never called because all instances of the object are created // with "new", yet none are ever destroyed with "delete". As an alternative to this behavior // the delete method should recursively delete mNextBlock, if it's non-NULL, prior to // returning. It seems unnecessary to do this, however, since the whole idea behind this // class is that it's a simple implementation of one-time, persistent memory allocation. // It's not intended to permit deallocation and subsequent reclamation of freed fragments // within the collection of blocks. When the program exits, all memory dynamically // allocated by the constructor and any other methods that call "new" will be reclaimed // by the OS. UPDATE: This is now called by static method DeleteAll(). { if (mBlock) // v1.0.40.04 free(mBlock); return; } diff --git a/source/script.cpp b/source/script.cpp index f60aaf6..11cfdb3 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -9369,1388 +9369,1393 @@ ResultType Script::DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]) // Vars could be supported here via FindVar(), but only globals ABOVE this point in // the script would be supported (since other globals don't exist yet). So it seems // best to wait until full/comprehensive support for expressions is studied/designed // for both static initializers and parameter-default-values. switch(IsPureNumeric(buf, true, false, true)) { case PURE_INTEGER: // It's always been somewhat inconsistent that for parameter default values, // numbers like 0xFF and 0123 do not preserve their formatting (unlike func(0123) // and y:=0xFF, which do preserve it). But for backward compatibility and // performance, it seems best to keep it this way. this_param.default_type = PARAM_DEFAULT_INT; this_param.default_int64 = ATOI64(buf); break; case PURE_FLOAT: this_param.default_type = PARAM_DEFAULT_FLOAT; this_param.default_double = ATOF(buf); break; default: // Not numeric (and also not a quoted string because that was handled earlier). return ScriptError(_T("Unsupported parameter default."), aBuf); } } } param_must_have_default = true; // For now, all other params after this one must also have default values. // Set up for the next iteration: param_start = omit_leading_whitespace(param_end); } else // This parameter does not have a default value specified. { if (param_must_have_default) return ScriptError(_T("Parameter default required."), this_param.var->mName); ++func.mMinParams; } ++param_count; if (*param_start != ',' && *param_start != ')') // Something like "fn(a, b c)" (missing comma) would cause this. return ScriptError(ERR_MISSING_COMMA, aBuf); // Reporting aBuf vs. param_start seems more informative since Vicinity isn't shown. if (*param_start == ',') { param_start = omit_leading_whitespace(param_start + 1); if (*param_start == ')') // If *param_start is ',' it will be caught as an error by the next iteration. return ScriptError(ERR_BLANK_PARAM, aBuf); // Reporting aBuf vs. param_start seems more informative since Vicinity isn't shown. } //else it's ')', in which case the next iteration will handle it. // Above has ensured that param_start now points to the next parameter, or ')' if none. } // for() each formal parameter. if (param_count) { // Allocate memory only for the actual number of parameters actually present. size_t size = param_count * sizeof(param[0]); if ( !(func.mParam = (FuncParam *)SimpleHeap::Malloc(size)) ) return ScriptError(ERR_OUTOFMEM); func.mParamCount = param_count - func.mIsVariadic; // i.e. don't count the final "param*" of a variadic function. memcpy(func.mParam, param, size); } //else leave func.mParam/mParamCount set to their NULL/0 defaults. // Indicate success: func.mGlobalVar = aFuncGlobalVar; // Give func.mGlobalVar its address, to be used for any var declarations inside this function's body. return OK; } ResultType Script::DefineClass(LPTSTR aBuf) { if (mClassObjectCount == MAX_NESTED_CLASSES) return ScriptError(_T("This class definition is nested too deep."), aBuf); LPTSTR cp, class_name = aBuf; Object *outer_class, *base_class = NULL; Object *&class_object = mClassObject[mClassObjectCount]; // For convenience. Var *class_var; ExprTokenType token; for (cp = aBuf; *cp && !IS_SPACE_OR_TAB(*cp); ++cp); if (*cp) { *cp = '\0'; // Null-terminate here for class_name. cp = omit_leading_whitespace(cp + 1); if (_tcsnicmp(cp, _T("extends"), 7) || !IS_SPACE_OR_TAB(cp[7])) return ScriptError(_T("Syntax error in class definition."), cp); LPTSTR base_class_name = omit_leading_whitespace(cp + 8); if (!*base_class_name) return ScriptError(_T("Missing class name."), cp); if ( !(base_class = FindClass(base_class_name)) ) { // This class hasn't been defined yet, but it might be. Automatically create the // class, but store it in the "unresolved" list. When its definition is encountered, // it will be removed from the list. If any classes remain in the list when the end // of the script is reached, an error will be thrown. if (mUnresolvedClasses && mUnresolvedClasses->GetItem(token, base_class_name)) { // Some other class has already referenced it. Use the existing object: base_class = (Object *)token.object; } else { if ( !mUnresolvedClasses && !(mUnresolvedClasses = Object::Create()) || !(base_class = Object::Create()) // Storing the file/line index in "__Class" instead of something like "DBG" or // two separate fields helps to reduce code size and maybe memory fragmentation. // It will be overwritten when the class definition is encountered. || !base_class->SetItem(_T("__Class"), ((__int64)mCurrFileIndex << 32) | mCombinedLineNumber) || !mUnresolvedClasses->SetItem(base_class_name, base_class) ) return ScriptError(ERR_OUTOFMEM); } } } // Validate the name even if this is a nested definition, for consistency. if (!Var::ValidateName(class_name, DISPLAY_NO_ERROR)) return ScriptError(_T("Invalid class name."), class_name); class_object = NULL; // This initializes the entry in the mClassObject array. if (mClassObjectCount) // Nested class definition. { outer_class = mClassObject[mClassObjectCount - 1]; if (outer_class->GetItem(token, class_name)) // At this point it can only be an Object() created by a class definition. class_object = (Object *)token.object; } else // Top-level class definition. { *mClassName = '\0'; // Init. if ( !(class_var = FindOrAddVar(class_name)) ) return FAIL; if (class_var->IsObject()) // At this point it can only be an Object() created by a class definition. class_object = (Object *)class_var->Object(); else // Force the variable to be super-global rather than passing this flag to // FindOrAddVar: a prior reference to this variable may have created it as // an ordinary global. class_var->Scope() = VAR_DECLARE_SUPER_GLOBAL; } if (_tcslen(mClassName) + _tcslen(class_name) + 1 >= _countof(mClassName)) // +1 for '.' return ScriptError(_T("Full class name is too long.")); if (*mClassName) _tcscat(mClassName, _T(".")); _tcscat(mClassName, class_name); // For now, it seems more useful to detect a duplicate as an error rather than as // a continuation of the previous definition. Partial definitions might be allowed // in future, perhaps via something like "Class Foo continued". if (class_object) return ScriptError(_T("Duplicate class definition."), aBuf); token.symbol = SYM_STRING; token.marker = mClassName; if (mUnresolvedClasses) { ExprTokenType result_token, *param = &token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; // Search for class and simultaneously remove it from the unresolved list: mUnresolvedClasses->_Remove(result_token, &param, 1); // result_token := mUnresolvedClasses.Remove(token) // If a field was found/removed, it can only be SYM_OBJECT. if (result_token.symbol == SYM_OBJECT) { // Use this object as the class. At least one other object already refers to it as mBase. // At this point class_object["__Class"] contains the file index and line number, but it // will be overwritten below. class_object = (Object *)result_token.object; } } if ( !(class_object || (class_object = Object::Create())) || !(class_object->SetItem(_T("__Class"), token)) || !(mClassObjectCount ? outer_class->SetItem(class_name, class_object) // Assign to super_class[class_name]. : class_var->Assign(class_object)) ) // Assign to global variable named %class_name%. return ScriptError(ERR_OUTOFMEM); class_object->SetBase(base_class); // May be NULL. ++mClassObjectCount; return OK; } ResultType Script::DefineClassProperty(LPTSTR aBuf) { LPTSTR name_end = find_identifier_end(aBuf); if (*name_end == '.') return ScriptError(ERR_INVALID_LINE_IN_CLASS_DEF, aBuf); LPTSTR param_start = omit_leading_whitespace(name_end); if (*param_start == '[') { LPTSTR param_end = aBuf + _tcslen(aBuf); if (param_end[-1] != ']') return ScriptError(ERR_MISSING_CLOSE_BRACKET, aBuf); *param_start = '('; param_end[-1] = ')'; } else param_start = _T("()"); // Save the property name and parameter list for later use with DefineFunc(). mClassPropertyDef = tmalloc(_tcslen(aBuf) + 7); // +7 for ".Get()\0" if (!mClassPropertyDef) return ScriptError(ERR_OUTOFMEM); _stprintf(mClassPropertyDef, _T("%.*s.Get%s"), int(name_end - aBuf), aBuf, param_start); Object *class_object = mClassObject[mClassObjectCount - 1]; *name_end = 0; // Terminate for aBuf use below. if (class_object->GetItem(ExprTokenType(), aBuf)) return ScriptError(ERR_DUPLICATE_DECLARATION, aBuf); mClassProperty = new Property(); if (!mClassProperty || !class_object->SetItem(aBuf, mClassProperty)) return ScriptError(ERR_OUTOFMEM); return OK; } ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic) { Object *class_object = mClassObject[mClassObjectCount - 1]; LPTSTR item, item_end; TCHAR orig_char, buf[LINE_SIZE]; size_t buf_used = 0; ExprTokenType temp_token, empty_token, int_token; empty_token.symbol = SYM_STRING; empty_token.marker = _T(""); int_token.symbol = SYM_INTEGER; // Value used to mark instance variables. int_token.value_int64 = 1; // for (item = omit_leading_whitespace(aBuf); *item;) // FOR EACH COMMA-SEPARATED ITEM IN THE DECLARATION LIST. { for (item_end = item; cisalnum(*item_end) || *item_end == '_'; ++item_end); // Find end of identifier. if (item_end == item) return ScriptError(ERR_INVALID_CLASS_VAR, item); orig_char = *item_end; *item_end = '\0'; // Temporarily terminate. bool item_exists = class_object->GetItem(temp_token, item); if (orig_char == '.') { *item_end = orig_char; // Undo termination. // This is something like "object.key := 5", which is only valid if "object" was // previously declared (and will presumably be assigned an object at runtime). // Ensure that at least the root class var exists; any further validation would // be impossible since the object doesn't exist yet. if (!item_exists) return ScriptError(_T("Unknown class var."), item); for (TCHAR *cp; *item_end == '.'; item_end = cp) { for (cp = item_end + 1; cisalnum(*cp) || *cp == '_'; ++cp); if (cp == item_end + 1) // This '.' wasn't followed by a valid identifier. Leave item_end // pointing at '.' and allow the switch() below to report the error. break; } } else { if (item_exists) return ScriptError(ERR_DUPLICATE_DECLARATION, item); // Assign class_object[item] := "" to mark it as a class variable // and allow duplicate declarations to be detected: if (!class_object->SetItem(item, aStatic ? empty_token : int_token)) return ScriptError(ERR_OUTOFMEM); *item_end = orig_char; // Undo termination. } size_t name_length = item_end - item; // This section is very similar to the one in ParseAndAddLine() which deals with // variable declarations, so maybe maintain them together: item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'. switch (*item_end) { case ',': // No initializer is present for this variable, so move on to the next one. item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration. continue; // No further processing needed below. case '\0': // No initializer is present for this variable, so move on to the next one. item = item_end; // Set "item" for use by the loop's condition. continue; case '=': // Supported for consistency with v1 syntax; to be removed in v2. ++item_end; // Point to the character after the "=". break; case ':': if (item_end[1] == '=') { item_end += 2; // Point to the character after the ":=". break; } // Otherwise, fall through to below: default: return ScriptError(ERR_INVALID_CLASS_VAR, item); } // Since above didn't "continue", this declared variable also has an initializer. // Append the class name, ":=" and initializer to pending_buf, to be turned into // an expression below, and executed at script start-up. item_end = omit_leading_whitespace(item_end); LPTSTR right_side_of_operator = item_end; // Save for use below. item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string). // Append "ClassNameOrThis.VarName := Initializer, " to the buffer. int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ") , aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator); if (chars_written < 0) return ScriptError(_T("Declaration too long.")); // Short message since should be rare. buf_used += chars_written; // Set "item" for use by the next iteration: item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list. ? omit_leading_whitespace(item_end + 1) : item_end; // It's the terminator, so let the loop detect that to finish. } if (buf_used) { // Above wrote at least one initializer expression into buf. buf[buf_used -= 2] = '\0'; // Remove the final ", " // The following section temporarily replaces mLastLine in order to insert script lines // either at the end of the list of static initializers (separate from the main script) // or at the end of the __Init method belonging to this class. Save the current values: Line *script_first_line = mFirstLine, *script_last_line = mLastLine; Line *block_end; Func *init_func = NULL; if (aStatic) { mLastLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } else { ExprTokenType token; if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT && (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability. { // __Init method already exists, so find the end of its body. for (block_end = init_func->mJumpToLine; block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute; block_end = block_end->mNextLine); } else { // Create an __Init method for this class. TCHAR def[] = _T("__Init()"); if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN) || (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation. return FAIL; mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out. init_func = g->CurrentFunc; init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions. if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL. return FAIL; block_end = mLastLine; block_end->mLineNumber = 0; // See above. // These must be updated as one or both have changed: script_first_line = mFirstLine; script_last_line = mLastLine; } g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this. mLastLine = block_end->mPrevLine; // i.e. insert before block_end. mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless. mCurrLine = NULL; // Fix for v1.1.09.02: Leaving this non-NULL at best causes error messages to show irrelevant vicinity lines, and at worst causes a crash because the linked list is in an inconsistent state. } if (!ParseAndAddLine(buf, ACT_EXPRESSION)) return FAIL; // Above already displayed the error. if (aStatic) { if (!mFirstStaticLine) mFirstStaticLine = mLastLine; mLastStaticLine = mLastLine; // The following is necessary if there weren't any executable lines above this static // initializer (i.e. mFirstLine was NULL and has been set to the newly created line): mFirstLine = script_first_line; } else { if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class. init_func->mJumpToLine = mLastLine; // Rejoin the function's block-end (and any lines following it) to the main script. mLastLine->mNextLine = block_end; block_end->mPrevLine = mLastLine; // mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our // __init function's block-begin, which is now the very first executable line in the script. g->CurrentFunc = NULL; } // Restore mLastLine so that any subsequent script lines are added at the correct point. mLastLine = script_last_line; } return OK; } Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength) { if (!aClassNameLength) aClassNameLength = _tcslen(aClassName); if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH) return NULL; LPTSTR cp, key; ExprTokenType token; Object *base_object = NULL; TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing. // Make temporary copy which we can modify. tmemcpy(class_name, aClassName, aClassNameLength); class_name[aClassNameLength] = '.'; // To simplify parsing. class_name[aClassNameLength + 1] = '\0'; // Get base variable; e.g. "MyClass" in "MyClass.MySubClass". cp = _tcschr(class_name + 1, '.'); Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL); if (!base_var) return NULL; // Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time: if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) ) return NULL; // Even if the loop below has no iterations, it initializes 'key' to the appropriate value: for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2. { if (cp == key) return NULL; // ScriptError(_T("Missing name."), cp); *cp = '\0'; // Terminate at the delimiting dot. if (!base_object->GetItem(token, key)) return NULL; base_object = (Object *)token.object; // See comment about Object() above. } return base_object; } Object *Object::GetUnresolvedClass(LPTSTR &aName) // This method is only valid for mUnresolvedClass. { if (!mFieldCount) return NULL; aName = mFields[0].key.s; return (Object *)mFields[0].object; } ResultType Script::ResolveClasses() { LPTSTR name; Object *base = mUnresolvedClasses->GetUnresolvedClass(name); if (!base) return OK; // There is at least one unresolved class. ExprTokenType token; if (base->GetItem(token, _T("__Class"))) { // In this case (an object in the mUnresolvedClasses list), it is always an integer // containing the file index and line number: mCurrFileIndex = int(token.value_int64 >> 32); mCombinedLineNumber = LineNumberType(token.value_int64); } mCurrLine = NULL; return ScriptError(_T("Unknown class."), name); } #ifndef AUTOHOTKEYSC struct FuncLibrary { LPTSTR path; DWORD_PTR length; }; Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude) // Caller must ensure that aFuncName doesn't already exist as a defined function. // If aFuncNameLength is 0, the entire length of aFuncName is used. { aErrorWasShown = false; // Set default for this output parameter. aFileWasFound = false; int i; LPTSTR char_after_last_backslash, terminate_here; TCHAR buf[MAX_PATH+1]; DWORD attr; TextMem tmem; TextMem::Buffer textbuf(NULL, 0, false); #define FUNC_LIB_EXT _T(".ahk") #define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1) #define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash. #define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1) #define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash. #define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1) #define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash. #define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1) #define FUNC_LIB_COUNT 4 static FuncLibrary sLib[FUNC_LIB_COUNT] = {0}; static LPTSTR winapi; if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance. { LPVOID aDataBuf; - HRSRC hResInfo = NULL; - DecompressBuffer(LockResource(LoadResource(g_hInstance, FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10)))), aDataBuf, g_default_pwd); + HRSRC hResInfo = FindResource(g_hInstance, _T("WINAPI"), MAKEINTRESOURCE(10)); + DecompressBuffer(LockResource(LoadResource(g_hInstance, hResInfo)), aDataBuf, g_default_pwd); #ifdef _UNICODE winapi = UTF8ToWide((LPCSTR)aDataBuf); #else winapi = (LPTSTR)aDataBuf; #endif for (i = 0; i < FUNC_LIB_COUNT; ++i) #ifdef _USRDLL if ( !(sLib[i].path = tmalloc(MAX_PATH)) ) // When dll script is restarted, SimpleHeap is deleted and we don't want to delete static memberst #else if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name. #endif return NULL; // Due to rarity, simply pass the failure back to caller. FuncLibrary *this_lib; // DETERMINE PATH TO "LOCAL" LIBRARY: this_lib = sLib; // For convenience and maintainability. this_lib->length = BIV_ScriptDir(NULL, _T("")); if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH) { this_lib->length = BIV_ScriptDir(this_lib->path, _T("")); _tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB); this_lib->length += FUNC_LOCAL_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "USER" LIBRARY: this_lib++; // For convenience and maintainability. this_lib->length = BIV_MyDocuments(this_lib->path, _T("")); if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB); this_lib->length += FUNC_USER_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "STANDARD" LIBRARY: this_lib++; // For convenience and maintainability. GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe. char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked. this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash. if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB); this_lib->length += FUNC_STD_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY: this_lib++; // For convenience and maintainability. BIV_AhkPath(this_lib->path, _T("")); _tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk")); *(_tcsrchr(this_lib->path,'\\')+8) = '\0'; CoInitialize(NULL); IShellLink *psl; if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) { #ifdef UNICODE if (SUCCEEDED(ppf->Load(this_lib->path, 0))) #else WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed. ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes. if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0))) #endif { TCHAR buf[MAX_PATH+1]; psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY); _tcscpy(this_lib->path,buf); _tcscpy(this_lib->path + _tcslen(buf),_T("\\\0")); } ppf->Release(); } psl->Release(); } CoUninitialize(); if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') ) { this_lib->length = 0; *this_lib->path = '\0'; } else this_lib->length = _tcslen(this_lib->path); for (i = 0; i < FUNC_LIB_COUNT; ++i) { attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code. if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order. { *sLib[i].path = '\0'; // Mark this library as disabled. sLib[i].length = 0; // } } } // Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library"). if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1]; LPTSTR naked_filename = aFuncName; // Set up for the first iteration. size_t naked_filename_length = aFuncNameLength; // for (int second_iteration = 0; second_iteration < 2; ++second_iteration) { for (i = 0; i < FUNC_LIB_COUNT; ++i) { if (!*sLib[i].path) // Library is marked disabled, so skip it. continue; if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH) continue; // Path too long to match in this library, but try others. dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path. _tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension. attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern. if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order. continue; aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found. // Since above didn't "continue", a file exists whose name matches that of the requested function. // Before loading/including that file, set the working directory to its folder so that if it uses // #Include, it will be able to use more convenient/intuitive relative paths. This is similar to // the "#Include DirName" feature. // Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like // C: that lacks a backslash (see SetWorkingDir() for details). terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library. *terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir(). SetWorkingDir(sLib[i].path); // See similar section in the #Include directive. *terminate_here = '\\'; // Undo the termination. if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude) { // For each auto-included library-file, write out two #Include lines: // 1) Use #Include in its "change working directory" mode so that any explicit #include directives // or FileInstalls inside the library file itself will work consistently and properly. // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include // the library file itself. // We don't directly append library files onto the main script here because: // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files // might contain #Include even though it's rare). // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file // and deposited separately/synchronously into the temp-include file by some new logic at the // AutoHotkey.exe's code for the #Include directive. // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts. mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n") , sLib[i].length, sLib[i].path, sLib[i].path); // Now continue on normally so that our caller can continue looking for syntax errors. } // g->CurrentFunc is non-NULL when the function-call being resolved is inside // a function. Save and reset it for correct behaviour in the include file: Func *current_func = g->CurrentFunc; g->CurrentFunc = NULL; // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { g->CurrentFunc = current_func; // Restore. aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } g->CurrentFunc = current_func; // Restore. // Now that a matching filename has been found, it seems best to stop searching here even if that // file doesn't actually contain the requested function. This helps library authors catch bugs/typos. // HotKeyIt, override so resource can be tried too if (current_func = FindFunc(aFuncName, aFuncNameLength)) return current_func; continue; } // for() each library directory. // Now that the first iteration is done, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. break; // All loops are done because second iteration is the last possible attempt. naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). break; // All loops are done because second iteration is the last possible attempt. naked_filename = class_name_buf; // Point it to a buffer for use below. tmemcpy(naked_filename, aFuncName, naked_filename_length); naked_filename[naked_filename_length] = '\0'; } // 2-iteration for(). // HotKeyIt find library in Resource // Since above didn't return, no match found in any library. // Search in Resource for a library // // If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource // If nothing in dll resource is found, search again in main executable. tmemcpy(class_name_buf, aFuncName, aFuncNameLength); tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4); class_name_buf[aFuncNameLength + 4] = '\0'; HRSRC lib_hResource; BOOL aUseHinstance = true; if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) { // Now that the resource is not found, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. aUseHinstance = false; if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) ) { if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. goto winapi; else { naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). return NULL; tmemcpy(class_name_buf, aFuncName, naked_filename_length); tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4); class_name_buf[naked_filename_length + 4] = '\0'; if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) ) { if ( !(lib_hResource = FindResource(NULL, class_name_buf, _T("LIB"))) ) goto winapi; } else aUseHinstance = true; } } } // Now a resouce was found and it can be loaded HGLOBAL hResData; HINSTANCE ahInstance = aUseHinstance ? g_hInstance : NULL; if ( !( (textbuf.mLength = SizeofResource(ahInstance, lib_hResource)) && (hResData = LoadResource(ahInstance, lib_hResource)) && (textbuf.mBuffer = LockResource(hResData)) ) ) { // aErrorWasShown = true; // Do not display errors here goto winapi; } if (*(unsigned int*)textbuf.mBuffer == 0x04034b50) { LPVOID aDataBuf; DWORD aSizeDeCompressed = DecompressBuffer(textbuf.mBuffer,aDataBuf); if (aSizeDeCompressed) { LPVOID buff = _alloca(aSizeDeCompressed); // will be freed when function returns memmove(buff,aDataBuf,aSizeDeCompressed); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); textbuf.mLength = aSizeDeCompressed; textbuf.mBuffer = buff; } } aFileWasFound = true; // NOTE: Ahk2Exe strips off the UTF-8 BOM. LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR)); tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8); tmem.Read(resource_script, textbuf.mLength); // g->CurrentFunc is non-NULL when the function-call being resolved is inside // a function. Save and reset it for correct behaviour in the include file: Func *current_func = g->CurrentFunc; g->CurrentFunc = NULL; // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedText(resource_script, class_name_buf)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { g->CurrentFunc = current_func; // Restore. aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } g->CurrentFunc = current_func; // Restore. return FindFunc(aFuncName, aFuncNameLength); winapi: TCHAR parameter[1024] = { L'#', L'D', L'l', L'l', L'I', L'm', L'p', L'o', L'r', L't', L'\\' }; memmove(&parameter[11], aFuncName, aFuncNameLength*sizeof(TCHAR)); parameter[aFuncNameLength + 11] = L','; parameter[aFuncNameLength + 12] = '\0'; LPTSTR found; if (found = _tcsstr(winapi, (LPTSTR)&parameter[10])) { parameter[10] = L','; LPTSTR aDest = (LPTSTR)&parameter[aFuncNameLength + 12]; LPTSTR aDllName = _tcsstr(found, _T("\t")) + 1; size_t aNameLen = _tcsstr(aDllName, _T("\\")) - aDllName + 1; _tcsncpy(aDest, aDllName, aNameLen); aDest = aDest + aNameLen; _tcsncpy(aDest, found + 1, aFuncNameLength + 1); aDest = aDest + aFuncNameLength + 1; for (found = _tcsstr(found, _T(",")) + 1; *found != L'\\'; found++) { if (*found == L'U' || *found == L'u') { *aDest = L'U'; aDest++; continue; } if (*found == L's' || *found == L'S') { _tcscpy(aDest, _T("STR")); aDest = aDest + 3; } else if (*found == L't' || *found == L't') { _tcscpy(aDest, _T("PTR")); aDest = aDest + 3; } else if (*found == L'a' || *found == L'A') { _tcscpy(aDest, _T("ASTR")); aDest = aDest + 4; } else if (*found == L'w' || *found == L'W') { _tcscpy(aDest, _T("WSTR")); aDest = aDest + 4; } else if (*found == L'x' || *found == L'X') //TCHAR { #ifdef _UNICODE _tcscpy(aDest, _T("USHORT")); aDest = aDest + 6; #else _tcscpy(aDest, _T("UCHAR")); aDest = aDest + 5; #endif } else if ((*found == L'i' || *found == L'I') && *(found + 1) == L'6') { _tcscpy(aDest, _T("INT64")); aDest = aDest + 5; found++; } else if (*found == L'i' || *found == L'I') { - _tcscpy(aDest, _T("INT")); - aDest = aDest + 3; + if (*(found + 1) != L'\\') + { // Default Return type int, no need to define + _tcscpy(aDest, _T("INT")); + aDest = aDest + 3; + } + else // remove last , since no return type is given + aDest--; } else if (*found == L'h' || *found == L'H') { _tcscpy(aDest, _T("SHORT")); aDest = aDest + 5; } else if (*found == L'c' || *found == L'C') { _tcscpy(aDest, _T("CHAR")); aDest = aDest + 4; } else if (*found == L'f' || *found == L'F') { _tcscpy(aDest, _T("FLOAT")); aDest = aDest + 5; } else if (*found == L'd' || *found == L'D') { _tcscpy(aDest, _T("DOUBLE")); aDest = aDest + 6; } if (*(found + 1) == L'*' || *(found + 1) == L'p' || *(found + 1) == L'P') { *aDest = *found; aDest++; } _tcscpy(aDest, _T(",,")); aDest = aDest + 2; } *(aDest - 2) = L'\0'; LoadDllFunction(_tcschr(parameter, L',') + 1, parameter); return FindFunc(aFuncName, aFuncNameLength); } return NULL; } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } else if (!_tcsicmp(func_name, _T("Struct"))) { bif = BIF_Struct; min_params = 1; max_params = 3; } else if (!_tcsicmp(func_name, _T("Sizeof"))) { bif = BIF_sizeof; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("UnZipRawMemory"))) // lowlevel() Naveen v9. { bif = BIF_UnZipRawMemory; min_params = 1; max_params = 3; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } else if (!_tcsicmp(func_name, _T("StrSplit"))) { bif = BIF_StrSplit; min_params = 1; max_params = 3; } else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; } else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 5; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryFindResource"))) { bif = BIF_MemoryFindResource; min_params = 3; max_params = 4; } else if (!_tcsicmp(func_name, _T("MemorySizeOfResource"))) { bif = BIF_MemorySizeOfResource; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryLoadResource"))) { bif = BIF_MemoryLoadResource; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryLoadString"))) { bif = BIF_MemoryLoadString; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1.
tinku99/ahkdll
444e306e8f853699343ef74a766329ef0dbaea4d
Fixed several memory leaks
diff --git a/source/SimpleHeap.cpp b/source/SimpleHeap.cpp index b526310..21a9f6c 100644 --- a/source/SimpleHeap.cpp +++ b/source/SimpleHeap.cpp @@ -1,185 +1,206 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 "SimpleHeap.h" #include "globaldata.h" // for g_script, so that errors can be centrally reported here. // Static member data: SimpleHeap *SimpleHeap::sFirst = NULL; -SimpleHeap *SimpleHeap::sLast = NULL; +SimpleHeap *SimpleHeap::sLast = NULL; char *SimpleHeap::sMostRecentlyAllocated = NULL; UINT SimpleHeap::sBlockCount = 0; SimpleHeap **sBlocks; LPTSTR SimpleHeap::Malloc(LPTSTR aBuf, size_t aLength) // v1.0.44.14: Added aLength to improve performance in cases where callers already know the length. // If aLength is at its default of -1, the length will be calculated here. // Caller must ensure that aBuf isn't NULL. { if (!aBuf || !*aBuf) // aBuf is checked for NULL because it's not worth avoiding it for such a low-level, frequently-called function. return _T(""); // Return the constant empty string to the caller (not aBuf itself since that might be volatile). if (aLength == -1) // Caller wanted us to calculate it. Compare directly to -1 since aLength is unsigned. aLength = _tcslen(aBuf); LPTSTR new_buf; - if ( !(new_buf = (LPTSTR)SimpleHeap::Malloc((aLength + 1) * sizeof(TCHAR))) ) // +1 for the zero terminator. + if (!(new_buf = (LPTSTR)SimpleHeap::Malloc((aLength + 1) * sizeof(TCHAR)))) // +1 for the zero terminator. { g_script.ScriptError(ERR_OUTOFMEM, aBuf); return NULL; // Callers may rely on NULL vs. "" being returned in the event of failure. } if (aLength) tmemcpy(new_buf, aBuf, aLength); // memcpy() typically benchmarks slightly faster than strcpy(). //else only a terminator is needed. new_buf[aLength] = '\0'; // Terminate here for when aLength==0 and for the memcpy above so that caller's aBuf doesn't have to be terminated. return new_buf; } void* SimpleHeap::Malloc(size_t aSize) // This could be made more memory efficient by searching old blocks for sufficient // free space to handle <size> prior to creating a new block. But the whole point // of this class is that it's only called to allocate relatively small objects, // such as the lines of text in a script file. The length of such lines is typically // around 80, and only rarely would exceed 1000. Trying to find memory in old blocks // seems like a bad trade-off compared to the performance impact of traversing a // potentially large linked list or maintaining and traversing an array of // "under-utilized" blocks. { if (aSize < 1 || aSize > BLOCK_SIZE) return NULL; if (!sFirst) // We need at least one block to do anything, so create it. - if ( !(sFirst = CreateBlock()) ) + if (!(sFirst = CreateBlock())) return NULL; if (aSize > sLast->mSpaceAvailable) - if ( !(sLast->mNextBlock = CreateBlock()) ) + if (!(sLast->mNextBlock = CreateBlock())) return NULL; sMostRecentlyAllocated = sLast->mFreeMarker; // THIS IS NOW THE NEWLY ALLOCATED BLOCK FOR THE CALLER, which is 32-bit aligned because the previous call to this function (i.e. the logic below) set it up that way. // v1.0.40.04: Set up the NEXT chunk to be aligned on a 32-bit boundary (the first chunk in each block // should always be aligned since the block's address came from malloc()). On average, this change // "wastes" only 1.5 bytes per chunk. In a 200 KB script of typical contents, this change requires less // than 8 KB of additional memory (as shown by temporarily making BLOCK_SIZE a smaller value such as 8 KB // for a more accurate measurement). That cost seems well worth the following benefits: // 1) Solves failure of API functions like GetRawInputDeviceList() when passed a non-aligned address. // 2) May solve other obscure issues (past and future), which improves sanity due to not chasing bugs // for hours on end that were caused solely by non-alignment. // 3) May slightly improve performance since aligned data is easier for the CPU to access and cache. size_t remainder = aSize % sizeof(void *); size_t size_consumed = remainder ? aSize + (sizeof(void *) - remainder) : aSize; // v1.0.45: The following can't happen when BLOCK_SIZE is a multiple of 4, so it's commented out: //if (size_consumed > sLast->mSpaceAvailable) // For maintainability, don't allow mFreeMarker to go out of bounds or // size_consumed = sLast->mSpaceAvailable; // mSpaceAvailable to go negative (which it can't due to be unsigned). sLast->mFreeMarker += size_consumed; sLast->mSpaceAvailable -= size_consumed; return (void *)sMostRecentlyAllocated; } void SimpleHeap::Delete(void *aPtr) // If aPtr is the most recently allocated area of memory by SimpleHeap, this will reclaim that // memory. Otherwise, the caller should realize that the memory cannot be reclaimed (i.e. potential // memory leak unless caller handles things right). { if (aPtr != sMostRecentlyAllocated || !sMostRecentlyAllocated) return; size_t sMostRecentlyAllocated_size = sLast->mFreeMarker - sMostRecentlyAllocated; sLast->mFreeMarker -= sMostRecentlyAllocated_size; sLast->mSpaceAvailable += sMostRecentlyAllocated_size; sMostRecentlyAllocated = NULL; // i.e. no support for anything other than a one-time delete of an item just added. } // Commented out because not currently used: void SimpleHeap::DeleteAll() // See Hotkey::AllDestructAndExit for comments about why this isn't actually called. { +#ifdef _USRDLL EnterCriticalSection(&g_CriticalHeapBlocks); +#endif if (sBlocks) // don't process again if we already freed Heap { - for (;sBlockCount;) + for (; sBlockCount;) { if (sBlocks[--sBlockCount]) delete sBlocks[sBlockCount]; sBlocks[sBlockCount] = NULL; } sFirst = NULL; sLast = NULL; sMostRecentlyAllocated = NULL; free(sBlocks); sBlocks = NULL; } +#ifdef _USRDLL LeaveCriticalSection(&g_CriticalHeapBlocks); +#endif } SimpleHeap *SimpleHeap::CreateBlock() // Added for v1.0.40.04 to try to solve the fact that some functions such as GetRawInputDeviceList() // will sometimes fail if passed memory from SimpleHeap. Although this change didn't actually solve // the issue (it turned out to be a 32-bit alignment issue), using malloc() appears to save memory // (compared to using "new" on a class that contains a large buffer such as "char mBlock[BLOCK_SIZE]"). // In a 200 KB script, it saves 8 KB of VM Size as shown by Task Manager. { +#ifdef _USRDLL + EnterCriticalSection(&g_CriticalHeapBlocks); +#endif SimpleHeap *block; - if ( !(block = new SimpleHeap) ) + if (!(block = new SimpleHeap)) + { +#ifdef _USRDLL + LeaveCriticalSection(&g_CriticalHeapBlocks); +#endif return NULL; + } // The new block's mFreeMarker starts off pointing to the first byte in the new block: - if ( !(block->mBlock = block->mFreeMarker = (char *)malloc(BLOCK_SIZE)) ) + if (!(block->mBlock = block->mFreeMarker = (char *)malloc(BLOCK_SIZE))) { delete block; +#ifdef _USRDLL + LeaveCriticalSection(&g_CriticalHeapBlocks); +#endif return NULL; } // Since above didn't return, block was successfully created: block->mSpaceAvailable = BLOCK_SIZE; sLast = block; // Constructing a new block always results in it becoming the current block. if (!sBlockCount || !(sBlockCount % 1024)) { SimpleHeap **new_Blocks; - if (!(new_Blocks = (SimpleHeap**)realloc(sBlocks,(!sBlockCount ? 1024 : sBlockCount * 2) * sizeof(SimpleHeap*)))) + if (!(new_Blocks = (SimpleHeap**)realloc(sBlocks, (!sBlockCount ? 1024 : sBlockCount * 2) * sizeof(SimpleHeap*)))) { delete block; +#ifdef _USRDLL + LeaveCriticalSection(&g_CriticalHeapBlocks); +#endif return NULL; } sBlocks = new_Blocks; } sBlocks[sBlockCount] = block; ++sBlockCount; +#ifdef _USRDLL + LeaveCriticalSection(&g_CriticalHeapBlocks); +#endif return block; } SimpleHeap::SimpleHeap() // Construct a new block. Caller is responsible for initializing other members. : mNextBlock(NULL) { } SimpleHeap::~SimpleHeap() // This destructor is currently never called because all instances of the object are created // with "new", yet none are ever destroyed with "delete". As an alternative to this behavior // the delete method should recursively delete mNextBlock, if it's non-NULL, prior to // returning. It seems unnecessary to do this, however, since the whole idea behind this // class is that it's a simple implementation of one-time, persistent memory allocation. // It's not intended to permit deallocation and subsequent reclamation of freed fragments // within the collection of blocks. When the program exits, all memory dynamically // allocated by the constructor and any other methods that call "new" will be reclaimed // by the OS. UPDATE: This is now called by static method DeleteAll(). { if (mBlock) // v1.0.40.04 free(mBlock); return; } diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 3563977..3149f8c 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,1121 +1,1127 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; + InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). + InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. + InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } - free(g_array); - // Unregister window class registered in Script::CreateWindows + DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. + DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. + DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. + if (scriptstring) + free(scriptstring); + if (Line::sMaxSourceFiles) + free(Line::sSourceFile); +#ifdef _DEBUG + free(g_Debugger.mStack.mBottom); +#endif #ifndef MINIDLL -#ifdef UNICODE - if (g_ClassRegistered) - UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); - if (g_ClassSplashRegistered) - UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); -#else - if (g_ClassRegistered) - UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); - if (g_ClassSplashRegistered) - UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); + if (g_input.MatchCount) + { + free(g_input.match); + } + if (g_script.mTrayMenu) + g_script.ScriptDeleteMenu(g_script.mTrayMenu); + free(g_KeyHistory); #endif -#endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif - InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). - InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. - InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. - if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { - struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); - HINSTANCE hInstance = a.hInstanceP; - LPTSTR fileName = a.name; - OldWinMain(hInstance, 0, fileName, 0); + OldWinMain(nameHinstanceP.hInstanceP, 0, nameHinstanceP.name, 0); g_script.Destroy(); + CloseHandle(hThread); + hThread = NULL; _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed + Sleep(50); int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } - hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); + hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, NULL, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); + HANDLE oldhThread = hThread; hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; + CloseHandle(oldhThread); _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; + CloseHandle(hThread); hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute || g_Reloading || g_Loading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) { if (IsUnicode==NULL) return ERROR_INVALID_PARAMETER; *IsUnicode = com_ahkIsUnicode(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) { // search for TypeLib in current dll WCHAR buf[MAX_PATH * sizeof(WCHAR)]; // LoadTypeLibEx needs Unicode string if (GetModuleFileNameW(g_hInstance, buf, _countof(buf))) hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); else // MemoryModule, search troug g_ListOfMemoryModules and use temp file to extract and load TypeLib file { HMEMORYMODULE hmodule = (HMEMORYMODULE)(g_hMemoryModule); HMEMORYRSRC res = MemoryFindResource(hmodule,_T("TYPELIB"),MAKEINTRESOURCE(1)); if (!res) return TYPE_E_INVALIDSTATE; DWORD resSize = MemorySizeOfResource(hmodule,res); // Path to temp directory + our temporary file name DWORD tempPathLength = GetTempPathW(MAX_PATH, buf); wcscpy(buf + tempPathLength,L"AutoHotkey.MemoryModule.temp.tlb"); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after LoadTypeLib has been called. HANDLE hFile = CreateFileW(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,MemoryLoadResource(hmodule,res),resSize,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to write data, continue and try loading } hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileW(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); } if (FAILED(hr)) return hr; } // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // diff --git a/source/globaldata.cpp b/source/globaldata.cpp index 47013a7..92dfa61 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,555 +1,557 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() // for compiled AutoHotkey.exe #ifdef _USRDLL bool g_Reloading = false; bool g_Loading = false; #endif HINSTANCE g_hInstance = NULL; // Set by WinMain(). HMODULE g_hMemoryModule = NULL; // Set by DllMain() used for COM DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; +#ifdef _USRDLL CRITICAL_SECTION g_CriticalHeapBlocks; +#endif CRITICAL_SECTION g_CriticalAhkFunction; UINT g_DefaultScriptCodepage = CP_ACP; bool g_ReturnNotExit; // for ahkExec/addScript/addFile bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL PVOID g_ExceptionHandler = NULL; SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. static int GetScreenDPI() { // The DPI setting can be different for each screen axis, but // apparently it is such a rare situation that it is not worth // supporting it. So we just retrieve the X axis DPI. HDC hdc = GetDC(NULL); int dpi = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); return dpi; } int g_ScreenDPI = GetScreenDPI(); MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; TCHAR g_default_pwd0; TCHAR g_default_pwd1; TCHAR g_default_pwd2; TCHAR g_default_pwd3; TCHAR g_default_pwd4; TCHAR g_default_pwd5; TCHAR g_default_pwd6; TCHAR g_default_pwd7; TCHAR g_default_pwd8; TCHAR g_default_pwd9; TCHAR *g_default_pwd[] = {&g_default_pwd0,&g_default_pwd1,&g_default_pwd2,&g_default_pwd3,&g_default_pwd4,&g_default_pwd5,&g_default_pwd6,&g_default_pwd7,&g_default_pwd8,&g_default_pwd9,0,0}; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("BreakIf"), 1, 2, 2, {1, 0}} , {_T("Continue"), 0, 1, 1, NULL}, {_T("ContinueIf"), 1, 2, 2, {1, 0}} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("Finally"), 0, 0, 0, NULL} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] diff --git a/source/globaldata.h b/source/globaldata.h index 6a86878..3a294de 100644 --- a/source/globaldata.h +++ b/source/globaldata.h @@ -1,372 +1,374 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" #ifdef _USRDLL extern bool g_Reloading; extern bool g_Loading; #endif extern HRSRC g_hResource; // for compiled AutoHotkey.exe extern HINSTANCE g_hInstance; extern HMODULE g_hMemoryModule; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; extern ATOM g_ClassRegistered; extern ATOM g_ClassSplashRegistered; extern CRITICAL_SECTION g_CriticalRegExCache; +#ifdef _USRDLL extern CRITICAL_SECTION g_CriticalHeapBlocks; +#endif extern CRITICAL_SECTION g_CriticalAhkFunction; extern UINT g_DefaultScriptCodepage; extern bool g_ReturnNotExit; // for ahkExec/addScript/addFile 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; #ifndef MINIDLL extern HWND g_hWndSplash; // The SplashText window. extern HFONT g_hFontSplash; #endif extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. 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. #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_HookReceiptOfLControlMeansAltGr; extern DWORD g_IgnoreNextLControlDown; extern DWORD g_IgnoreNextLControlUp; extern BYTE g_MenuMaskKey; // L38: See #MenuMaskKey. // 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_Warn_UseUnsetLocal; extern WarnMode g_Warn_UseUnsetGlobal; extern WarnMode g_Warn_UseEnv; extern WarnMode g_Warn_LocalSameAsGlobal; #ifndef MINIDLL extern PVOID g_ExceptionHandler; extern SingleInstanceType g_AllowOnlyOneInstance; #endif extern bool g_persistent; #ifndef MINIDLL extern bool g_NoTrayIcon; #endif #ifdef AUTOHOTKEYSC extern bool g_AllowMainWindow; #endif extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_AutoExecTimerExists; #ifndef MINIDLL extern bool g_InputTimerExists; #endif extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; #ifndef MINIDLL extern bool g_IsSuspended; #endif extern BOOL g_WriteCacheDisabledInt64; extern BOOL g_WriteCacheDisabledDouble; extern BOOL g_NoEnv; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; #ifndef MINIDLL extern int g_MaxHistoryKeys; #endif extern VarSizeType g_MaxVarCapacity; #ifndef MINIDLL extern UCHAR g_MaxThreadsPerHotkey; #endif extern int g_MaxThreadsTotal; #ifndef MINIDLL extern int g_MaxHotkeysPerInterval; extern int g_HotkeyThrottleInterval; #endif extern bool g_MaxThreadsBuffer; extern SendLevelType g_InputLevel; #ifndef MINIDLL extern HotCriterionType g_HotCriterion; extern LPTSTR g_HotWinTitle; extern LPTSTR g_HotWinText; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #if (expression). See globaldata.cpp for comments. extern int g_HotExprIndex; extern Line **g_HotExprLines; extern int g_HotExprLineCount; extern int g_HotExprLineCountMax; extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern int g_ScreenDPI; extern MenuTypeType g_MenuIsVisible; #endif extern int g_nMessageBoxes; #ifndef MINIDLL extern int g_nInputBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern InputBoxType g_InputBox[MAX_INPUTBOXES]; extern SplashType g_Progress[MAX_PROGRESS_WINDOWS]; extern SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS]; extern GuiType **g_gui; extern int g_guiCount, g_guiCountMax; #endif extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorStruct *g_MsgMonitor; // An array to be allocated upon first use (if any). extern int g_MsgMonitorCount; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern Func *g_SortFunc; extern TCHAR g_delimiter; extern TCHAR g_DerefChar; extern TCHAR g_EscapeChar; #ifndef MINIDLL // 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 bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSSendRaw; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; #endif // Global objects: extern Var *g_ErrorLevel; #ifndef MINIDLL extern input_type g_input; #endif EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; #ifndef MINIDLL extern int g_IconTray; extern int g_IconTraySuspend; #endif extern DWORD g_OriginalTimeout; EXTERN_G; extern global_struct g_default, *g_array; extern TCHAR g_WorkingDir[MAX_PATH]; // Explicit size needed here in .h file for use with sizeof(). extern LPTSTR g_WorkingDirOrig; extern bool g_ContinuationLTrim; 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; #ifndef MINIDLL extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; #endif extern DWORD g_TimeLastInputPhysical; #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE extern bool g_KeyHistoryToFile; #endif #endif // MINIDLL extern TCHAR g_default_pwd0; extern TCHAR g_default_pwd1; extern TCHAR g_default_pwd2; extern TCHAR g_default_pwd3; extern TCHAR g_default_pwd4; extern TCHAR g_default_pwd5; extern TCHAR g_default_pwd6; extern TCHAR g_default_pwd7; extern TCHAR g_default_pwd8; extern TCHAR g_default_pwd9; extern TCHAR *g_default_pwd[]; // 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. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ if (!g_AutoExecTimerExists)\ g_AutoExecTimerExists = SetTimer(g_hWnd, TIMER_ID_AUTOEXEC, aTimeoutValue, AutoExecSectionTimeout);\ } // v1.0.39 for above: Removed the call to ExitApp() upon failure. See SET_MAIN_TIMER for details. #ifndef MINIDLL #define SET_INPUT_TIMER(aTimeoutValue) \ if (!g_InputTimerExists)\ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); #endif // 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; // See above comment about g->AllowThreadToBeInterrupted. #define KILL_AUTOEXEC_TIMER \ {\ if (g_AutoExecTimerExists && KillTimer(g_hWnd, TIMER_ID_AUTOEXEC))\ g_AutoExecTimerExists = false;\ } #ifndef MINIDLL #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #endif #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif diff --git a/source/script.cpp b/source/script.cpp index e6b126e..f60aaf6 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,1146 +1,1175 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL), mClassProperty(NULL), mClassPropertyDef(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; +#ifdef _USRDLL + if (menu_to_delete != mTrayMenu) +#endif ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } +#ifdef _USRDLL + if (mFirstMenu != mTrayMenu) + { + mFirstMenu = NULL; + mLastMenu = NULL; + mTrayMenu = NULL; + } + else + { + mFirstMenu->mNextMenu = NULL; + mLastMenu = mFirstMenu; + } #endif +#endif // MINIDLL // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif + // We call DestroyWindow() because MainWindowProc() has left that up to us. + // DestroyWindow() will cause MainWindowProc() to immediately receive and process the + // WM_DESTROY msg, which should in turn result in any child windows being destroyed + // and other cleanup being done: + KILL_AUTOEXEC_TIMER + KILL_MAIN_TIMER + if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. + { + g_DestroyWindowCalled = true; + DestroyWindow(g_hWnd); + DestroyWindow(g_hWndEdit); + DeleteObject(g_hFontEdit); +#ifndef MINIDLL + if (g_hWndSplash) + DestroyWindow(g_hWndSplash); + if (g_hFontSplash) + DeleteObject(g_hFontSplash); + // Unregister window class registered in Script::CreateWindows +#ifdef UNICODE + if (g_ClassRegistered) + UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN, g_hInstance); + if (g_ClassSplashRegistered) + UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH, g_hInstance); +#else + if (g_ClassRegistered) + UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN, g_hInstance); + if (g_ClassSplashRegistered) + UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH, g_hInstance); +#endif +#endif // MINIDLL + } + if (g_hAccelTable) + DestroyAcceleratorTable(g_hAccelTable); if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL RemoveVectoredExceptionHandler(g_ExceptionHandler); // Exception handler to remove hooks to avoid system/mouse freeze #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL - DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // free Meta Object g_MetaObject.Free(); // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; for (v = 0; v < mVarCount; v++) { if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) mVar[v]->mObject->Release(); mVar[v]->ConvertToNonAliasIfNecessary(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; v++) { if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) mLazyVar[v]->mObject->Release(); mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; v++) { if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } for (v = 0; v < f.mVarCount; v++) { if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; v++) { if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } } // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); - // We call DestroyWindow() because MainWindowProc() has left that up to us. - // DestroyWindow() will cause MainWindowProc() to immediately receive and process the - // WM_DESTROY msg, which should in turn result in any child windows being destroyed - // and other cleanup being done: - KILL_AUTOEXEC_TIMER - KILL_MAIN_TIMER - if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. - { - g_DestroyWindowCalled = true; - DestroyWindow(g_hWnd); - DestroyWindow(g_hWndEdit); - DeleteObject(g_hFontEdit); -#ifndef MINIDLL - if (g_hWndSplash) - DestroyWindow(g_hWndSplash); - if (g_hFontSplash) - DeleteObject(g_hFontSplash); -#endif - } + #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); - DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if (!(g_array = (global_struct *)realloc(g_array,(g_MaxThreadsTotal + TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct)))) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once.
tinku99/ahkdll
5f5f3145de91ac4fbc4b486e72bb3e976a2ea90f
Revert to realloc g_array
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index ee18c9f..3563977 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,606 +1,607 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } + free(g_array); // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); g_script.Destroy(); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { diff --git a/source/script.cpp b/source/script.cpp index 0e78c0e..e6b126e 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -128,1456 +128,1455 @@ Script::Script() // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL RemoveVectoredExceptionHandler(g_ExceptionHandler); // Exception handler to remove hooks to avoid system/mouse freeze #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // free Meta Object g_MetaObject.Free(); // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; for (v = 0; v < mVarCount; v++) { if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) mVar[v]->mObject->Release(); mVar[v]->ConvertToNonAliasIfNecessary(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; v++) { if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) mLazyVar[v]->mObject->Release(); mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; v++) { if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } for (v = 0; v < f.mVarCount; v++) { if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; v++) { if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } } // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); #endif } #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif - free(g_array); } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: - if ( !(g_array = (global_struct *)malloc(g_array,(g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) + if (!(g_array = (global_struct *)realloc(g_array,(g_MaxThreadsTotal + TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct)))) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "background thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT); return OK; } #ifndef MINIDLL ResultType Script::Edit() { #ifdef AUTOHOTKEYSC return OK; // Do nothing. #else // This is here in case a compiled script ever uses the Edit command. Since the "Edit This // Script" menu item is not available for compiled scripts, it can't be called from there. TitleMatchModes old_mode = g->TitleMatchMode; g->TitleMatchMode = FIND_ANYWHERE; HWND hwnd = WinExist(*g, mFileName, _T(""), mMainWindowTitle, _T("")); // Exclude our own main window. g->TitleMatchMode = old_mode; if (hwnd) { TCHAR class_name[32]; GetClassName(hwnd, class_name, _countof(class_name)); if (!_tcscmp(class_name, _T("#32770")) || !_tcsnicmp(class_name, _T("AutoHotkey"), 10)) // MessageBox(), InputBox(), FileSelectFile(), or GUI/script-owned window. hwnd = NULL; // Exclude it from consideration. } if (hwnd) // File appears to already be open for editing, so use the current window. SetForegroundWindowEx(hwnd); else { TCHAR buf[MAX_PATH * 2]; // Enclose in double quotes anything that might contain spaces since the CreateProcess() // method, which is attempted first, is more likely to succeed. This is because it uses // the command line method of creating the process, with everything all lumped together: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) // Since this didn't work, try notepad. { // v1.0.40.06: Try to open .ini files first with their associated editor rather than trying the // "edit" verb on them: LPTSTR file_ext; if ( !(file_ext = _tcsrchr(mFileName, '.')) || _tcsicmp(file_ext, _T(".ini")) || !ActionExec(_T("open"), buf, mFileDir, false) ) // Relies on short-circuit boolean order. { // Even though notepad properly handles filenames with spaces in them under WinXP, // even without double quotes around them, it seems safer and more correct to always // enclose the filename in double quotes for maximum compatibility with all OSes: if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) MsgBox(_T("Could not open script.")); // Short message since so rare. } } } return OK; #endif } #endif // MINIDLL ResultType Script::Reload(bool aDisplayErrors) { // The new instance we're about to start will tell our process to stop, or it will display // a syntax error or some other error, in which case our process will still be running: #ifdef _USRDLL g_Reloading = true; //ExitApp(EXIT_RELOAD); reloadDll(); return EARLY_RETURN; #else #ifdef AUTOHOTKEYSC // This is here in case a compiled script ever uses the Reload command. Since the "Reload This // Script" menu item is not available for compiled scripts, it can't be called from there. return g_script.ActionExec(mOurEXE, _T("/restart"), g_WorkingDirOrig, aDisplayErrors); #else TCHAR arg_string[MAX_PATH + 512]; sntprintf(arg_string, _countof(arg_string), _T("/restart \"%s\""), mFileSpec); return g_script.ActionExec(mOurEXE, arg_string, g_WorkingDirOrig, aDisplayErrors); #endif // AUTOHOTKEYSC #endif // _USRDLL } ResultType Script::ExitApp(ExitReasons aExitReason, LPTSTR aBuf, int aExitCode) // Normal exit (if aBuf is NULL), or a way to exit immediately on error (which is mostly // for times when it would be unsafe to call MsgBox() due to the possibility that it would // make the situation even worse). { mExitReason = aExitReason; bool terminate_afterward = aBuf && !*aBuf; if (aBuf && *aBuf) { TCHAR buf[1024]; // No more than size-1 chars will be written and string will be terminated: sntprintf(buf, _countof(buf), _T("Critical Error: %s\n\n") WILL_EXIT, aBuf); // To avoid chance of more errors, don't use MsgBox(): MessageBox(g_hWnd, buf, g_script.mFileSpec, MB_OK | MB_SETFOREGROUND | MB_APPLMODAL); TerminateApp(aExitReason, CRITICAL_ERROR); // Only after the above. } // Otherwise, it's not a critical error. Note that currently, mOnExitLabel can only be // non-NULL if the script is in a runnable state (since registering an OnExit label requires // that a script command has executed to do it). If this ever changes, the !mIsReadyToExecute // condition should be added to the below if statement: static bool sExitLabelIsRunning = false; if (!mOnExitLabel || sExitLabelIsRunning) // || !mIsReadyToExecute { // In the case of sExitLabelIsRunning == true: // There is another instance of this function beneath us on the stack. Since we have // been called, this is a true exit condition and we exit immediately. // MUST NOT create a new thread when sExitLabelIsRunning because g_array allows only one // extra thread for ExitApp() (which allows it to run even when MAX_THREADS_EMERGENCY has // been reached). See TOTAL_ADDITIONAL_THREADS. #ifdef _USRDLL if (sExitLabelIsRunning && g_Reloading) { sExitLabelIsRunning = false; return EARLY_EXIT; } #endif g_AllowInterruption = FALSE; // In case TerminateApp releases objects and indirectly causes g->IsPaused = false; // more script to be executed. TerminateApp(aExitReason, aExitCode); } // Otherwise, the script contains the special RunOnExit label that we will run here instead // of exiting. And since it does, we know that the script is in a ready-to-execute state // because that is the only way an OnExit label could have been defined in the first place. // Usually, the RunOnExit subroutine will contain an Exit or ExitApp statement // which results in a recursive call to this function, but this is not required (e.g. the // Exit subroutine could display an "Are you sure?" prompt, and if the user chooses "No", // the Exit sequence can be aborted by simply not calling ExitApp and letting the thread // we create below end normally). // Next, save the current state of the globals so that they can be restored just prior // to returning to our caller: TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); // Save caller's errorlevel. InitNewThread(0, true, true, ACT_INVALID); // Uninterruptibility is handled below. Since this special thread should always run, no checking of g_MaxThreadsTotal is done before calling this. // Turn on uninterruptibility to forbid any hotkeys, timers, or user defined menu items // to interrupt. This is mainly done for peace-of-mind (since possible interactions due to // interruptions have not been studied) and the fact that this most users would not want this // subroutine to be interruptible (it usually runs quickly anyway). Another reason to make // it non-interruptible is that some OnExit subroutines might destruct things used by the // script's hotkeys/timers/menu items, and activating these items during the deconstruction // would not be safe. Finally, if a logoff or shutdown is occurring, it seems best to prevent // timed subroutines from running -- which might take too much time and prevent the exit from // occurring in a timely fashion. An option can be added via the FutureUse param to make it // interruptible if there is ever a demand for that. // UPDATE: g_AllowInterruption is now used instead of g->AllowThreadToBeInterrupted for two reasons: // 1) It avoids the need to do "int mUninterruptedLineCountMax_prev = g_script.mUninterruptedLineCountMax;" // (Disable this item so that ExecUntil() won't automatically make our new thread uninterruptible // after it has executed a certain number of lines). // 2) Mostly obsolete: If the thread we're interrupting is uninterruptible, the uninterruptible timer // might be currently pending. When it fires, it would make the OnExit subroutine interruptible // rather than the underlying subroutine. The above fixes the first part of that problem. // The 2nd part is fixed by reinstating the timer when the uninterruptible thread is resumed. // This special handling is only necessary here -- not in other places where new threads are // created -- because OnExit is the only type of thread that can interrupt an uninterruptible // thread. BOOL g_AllowInterruption_prev = g_AllowInterruption; // Save current setting. g_AllowInterruption = FALSE; // Mark the thread just created above as permanently uninterruptible (i.e. until it finishes and is destroyed). sExitLabelIsRunning = true; DEBUGGER_STACK_PUSH(mOnExitLabel->mJumpToLine, mOnExitLabel->mName) if (mOnExitLabel->Execute() == FAIL) { // If the subroutine encounters a failure condition such as a runtime error, exit immediately. // Otherwise, there will be no way to exit the script if the subroutine fails on each attempt. TerminateApp(aExitReason, aExitCode); } #ifdef _USRDLL if (aExitReason == EXIT_RELOAD) return EARLY_EXIT; #endif DEBUGGER_STACK_POP() sExitLabelIsRunning = false; // In case the user wanted the thread to end normally (see above). if (terminate_afterward) TerminateApp(aExitReason, aExitCode); // Otherwise: ResumeUnderlyingThread(ErrorLevel_saved); g_AllowInterruption = g_AllowInterruption_prev; // Restore original setting. return EARLY_EXIT; } void Script::TerminateApp(ExitReasons aExitReason, int aExitCode) // Note that g_script's destructor takes care of most other cleanup work, such as destroying // tray icons, menus, and unowned windows such as ToolTip. { #ifdef _USRDLL terminateDll(aExitCode); #else // L31: Release objects stored in variables, where possible. if (aExitCode != CRITICAL_ERROR) // i.e. Avoid making matters worse if CRITICAL_ERROR. { int v, i; for (v = 0; v < mVarCount; ++v) if (mVar[v]->IsObject()) mVar[v]->ReleaseObject(); for (v = 0; v < mLazyVarCount; ++v) if (mLazyVar[v]->IsObject()) mLazyVar[v]->ReleaseObject(); for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). // For consistency, only free static vars (see above). for (v = 0; v < f.mStaticVarCount; ++v) if (f.mStaticVar[v]->IsObject()) f.mStaticVar[v]->ReleaseObject(); for (v = 0; v < f.mStaticLazyVarCount; ++v) if (f.mStaticLazyVar[v]->IsObject()) f.mStaticLazyVar[v]->ReleaseObject(); // so no need to run below since static vars are in a separate array //for (v = 0; v < f.mVarCount; ++v) // if (f.mVar[v]->IsStatic() && f.mVar[v]->IsObject()) // f.mVar[v]->ReleaseObject(); //for (v = 0; v < f.mLazyVarCount; ++v) // if (f.mLazyVar[v]->IsStatic() && f.mLazyVar[v]->IsObject()) // f.mLazyVar[v]->ReleaseObject(); } } #ifdef CONFIG_DEBUGGER // L34: Exit debugger *after* the above to allow debugging of any invoked __Delete handlers. g_Debugger.Exit(aExitReason); #endif // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } Hotkey::AllDestructAndExit(aExitCode); #endif } #ifndef AUTOHOTKEYSC LineNumberType Script::LoadFromText(LPTSTR aScript,LPCTSTR aPathToShow, bool aCheckIfExpr) // HotKeyIt H1 LoadFromText() for text instead LoadFromFile() // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedText(aScript, aPathToShow) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { // Check for any unprocessed #if expressions: #ifndef MINIDLL #ifndef AUTOHOTKEYSC if (aCheckIfExpr) #endif for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < mFuncCount; ++i) { Func &func = *mFunc[i]; if (!func.mIsBuiltIn) { PreprocessLocalVars(func, func.mVar, func.mVarCount); PreprocessLocalVars(func, func.mStaticVar, func.mStaticVarCount); PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); PreprocessLocalVars(func, func.mStaticLazyVar, func.mStaticLazyVarCount); } } // Resolve any unresolved base classes. if (mUnresolvedClasses) { if (!ResolveClasses()) return LOADING_FAILED; mUnresolvedClasses->Release(); mUnresolvedClasses = NULL; } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine))
tinku99/ahkdll
c677873347998e88b56df169fe5a8015ce970b9e
WinApi (built-in list of winapi definitions)
diff --git a/source/resources/WINAPI.zip b/source/resources/WINAPI.zip new file mode 100644 index 0000000..9a4be7f Binary files /dev/null and b/source/resources/WINAPI.zip differ
tinku99/ahkdll
22c53bd2eb4196f3f96bd9ff55e75f43f3a21e18
Free MetaObject on exit for dll
diff --git a/source/script.cpp b/source/script.cpp index e3cf39f..aff460a 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,781 +1,783 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL), mClassProperty(NULL), mClassPropertyDef(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL RemoveVectoredExceptionHandler(g_ExceptionHandler); // Exception handler to remove hooks to avoid system/mouse freeze #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { + // free Meta Object + g_MetaObject.Free(); // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; for (v = 0; v < mVarCount; v++) { if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) mVar[v]->mObject->Release(); mVar[v]->ConvertToNonAliasIfNecessary(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; v++) { if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) mLazyVar[v]->mObject->Release(); mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; v++) { if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } for (v = 0; v < f.mVarCount; v++) { if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; v++) { if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } } // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); #endif } #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; diff --git a/source/script_object.h b/source/script_object.h index 7713c56..8e58bbf 100644 --- a/source/script_object.h +++ b/source/script_object.h @@ -1,475 +1,517 @@ #pragma once #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 IS_INVOKE_META (aFlags & IF_METAOBJ) #define SHOULD_INVOKE_METAFUNC (aFlags & IF_METAFUNC) #define INVOKE_NOT_HANDLED CONDITION_FALSE // // ObjectBase - Common base class, implements reference counting. // class DECLSPEC_NOVTABLE ObjectBase : public IObject { protected: ULONG mRefCount; 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; // 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; } 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() {} #ifdef CONFIG_DEBUGGER void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aDepth); #endif }; // // EnumBase - Base class for enumerator objects following standard syntax. // class EnumBase : public ObjectBase { public: ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); virtual int Next(Var *aOutputVar1, Var *aOutputVar2) = 0; }; +// +// Property: Invoked when a derived object gets/sets the corresponding key. +// + +class Property : public ObjectBase +{ +public: + Func *mGet, *mSet; + + bool CanGet() { return mGet; } + bool CanSet() { return mSet; } + + Property() : mGet(NULL), mSet(NULL) { } + + ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); +}; + + // // Object - Scriptable associative array. // class Object : public ObjectBase { protected: typedef INT_PTR IntKeyType; // Same size as the other union members. typedef INT_PTR IndexType; // Type of index for the internal array. Must be signed for FindKey to work correctly. union KeyType // Which of its members is used depends on the field's position in the mFields array. { LPTSTR s; IntKeyType i; IObject *p; }; struct FieldType { 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 struct { LPTSTR marker; // for SYM_OPERAND size_t size; // for SYM_OPERAND; allows reuse of allocated memory. For UNICODE: count in characters }; }; // key and symbol probably need to be adjacent to each other to conserve memory due to 8-byte alignment. KeyType key; SymbolType symbol; inline IntKeyType CompareKey(IntKeyType val) { return val - key.i; } // Used by both int and object since they are stored separately. inline int CompareKey(LPTSTR val) { return _tcsicmp(val, key.s); } bool Assign(LPTSTR str, size_t len = -1, bool exact_size = false); bool Assign(ExprTokenType &val); void Get(ExprTokenType &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. { aToken.value_int64 = n_int64; // Union copy. Overlaps with buf on x86 builds, so do it first. if ((aToken.symbol = symbol) == SYM_OPERAND) aToken.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } }; class Enumerator : public EnumBase { Object *mObject; IndexType mOffset; public: Enumerator(Object *aObject) : mObject(aObject), mOffset(-1) { mObject->AddRef(); } ~Enumerator() { mObject->Release(); } int Next(Var *aKey, Var *aVal); }; IObject *mBase; FieldType *mFields; IndexType mFieldCount, mFieldCountMax; // Current/max number of fields. // Holds the index of first key of a given type within mFields. 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 mFields // 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 IndexType mKeyOffsetInt = 0; IndexType mKeyOffsetObject, mKeyOffsetString; #ifdef CONFIG_DEBUGGER friend class Debugger; #endif Object() : mBase(NULL) , mFields(NULL), mFieldCount(0), mFieldCountMax(0) , mKeyOffsetObject(0), mKeyOffsetString(0) {} bool Delete(); ~Object(); template<typename T> FieldType *FindField(T val, IndexType left, IndexType right, IndexType &insert_pos); FieldType *FindField(SymbolType key_type, KeyType key, IndexType &insert_pos); FieldType *FindField(ExprTokenType &key_token, LPTSTR aBuf, SymbolType &key_type, KeyType &key, IndexType &insert_pos); FieldType *Insert(SymbolType key_type, KeyType key, IndexType at); bool SetInternalCapacity(IndexType new_capacity); bool Expand() // Expands mFields by at least one field. { return SetInternalCapacity(mFieldCountMax ? mFieldCountMax * 2 : 4); } ResultType CallField(FieldType *aField, ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); public: static Object *Create(ExprTokenType *aParam[] = NULL, int aParamCount = 0); bool Append(LPTSTR aValue, size_t aValueLength = -1); // Used by Func::Call() for variadic functions/function-calls: Object *Clone(BOOL aExcludeIntegerKeys = false); ResultType ArrayToParams(ExprTokenType *token, ExprTokenType **param_list, int extra_params, ExprTokenType **&aParam, int &aParamCount); ResultType ArrayToStrings(LPTSTR *aStrings, int &aStringCount, int aStringsMax); inline bool GetNextItem(ExprTokenType &aToken, INT_PTR &aOffset, INT_PTR &aKey) { if (++aOffset >= mKeyOffsetObject) // i.e. no more integer-keyed items. return false; FieldType &field = mFields[aOffset]; aKey = field.key.i; field.ToToken(aToken); return true; } int GetNumericItemCount() { return (int)mKeyOffsetObject; } bool GetItem(ExprTokenType &aToken, LPTSTR aKey) { KeyType key; SymbolType key_type = IsPureNumeric(aKey, FALSE, FALSE, FALSE); // SYM_STRING or SYM_INTEGER. if (key_type == SYM_INTEGER) key.i = ATOI(aKey); else key.s = aKey; IndexType insert_pos; FieldType *field = FindField(key_type, key, insert_pos); if (!field) return false; field->ToToken(aToken); return true; } bool SetItem(LPTSTR aKey, ExprTokenType &aValue) { KeyType key; SymbolType key_type = IsPureNumeric(aKey, FALSE, FALSE, FALSE); // SYM_STRING or SYM_INTEGER. if (key_type == SYM_INTEGER) key.i = ATOI(aKey); else key.s = aKey; IndexType insert_pos; FieldType *field = FindField(key_type, key, insert_pos); if ( !field && !(field = Insert(key_type, key, insert_pos)) ) // Relies on short-circuit boolean evaluation. return false; return field->Assign(aValue); } bool SetItem(LPTSTR aKey, __int64 aValue) { ExprTokenType token; token.symbol = SYM_INTEGER; token.value_int64 = aValue; return SetItem(aKey, token); } bool SetItem(LPTSTR aKey, IObject *aValue) { ExprTokenType token; token.symbol = SYM_OBJECT; token.object = aValue; return SetItem(aKey, token); } void ReduceKeys(INT_PTR aAmount) { for (IndexType i = 0; i < mKeyOffsetObject; ++i) mFields[i].key.i -= aAmount; } int MinIndex() { return (mKeyOffsetInt < mKeyOffsetObject) ? (int)mFields[0].key.i : 0; } int MaxIndex() { return (mKeyOffsetInt < mKeyOffsetObject) ? (int)mFields[mKeyOffsetObject-1].key.i : 0; } int Count() { return (int)mFieldCount; } bool HasNonnumericKeys() { return mKeyOffsetObject < mFieldCount; } void SetBase(IObject *aNewBase) { if (aNewBase) aNewBase->AddRef(); if (mBase) mBase->Release(); mBase = aNewBase; } IObject *Base() { return mBase; // Callers only want to call Invoke(), so no AddRef is done. } // Used by Object::_Insert() and Func::Call(): bool InsertAt(INT_PTR aOffset, INT_PTR aKey, ExprTokenType *aValue[], int aValueCount); void EndClassDefinition(); Object *GetUnresolvedClass(LPTSTR &aName); ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); ResultType _Insert(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _Remove(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _GetCapacity(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _SetCapacity(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _GetAddress(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _MaxIndex(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _MinIndex(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _Count(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _HasKey(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType _Clone(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); static LPTSTR sMetaFuncName[]; #ifdef CONFIG_DEBUGGER void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aDepth); #endif }; // // MetaObject: Used only by g_MetaObject (not every meta-object); see comments below. // class MetaObject : public Object { public: // In addition to ensuring g_MetaObject is never "deleted", this avoids a // tiny bit of work when any reference to this object is added or released. // Temporary references such as when evaluating "".base.foo are most common. ULONG STDMETHODCALLTYPE AddRef() { return 1; } ULONG STDMETHODCALLTYPE Release() { return 1; } bool Delete() { return false; } - +#ifdef _USRDLL + void Free() + { + if (mFields) + { + if (mFieldCount) + { + IndexType i = mFieldCount - 1; + // Free keys: first strings, then objects (objects have a lower index in the mFields array). + for (; i >= mKeyOffsetString; --i) + free(mFields[i].key.s); + for (; i >= mKeyOffsetObject; --i) + mFields[i].key.p->Release(); + // Free values. + while (mFieldCount) + mFields[--mFieldCount].Free(); + } + // Free fields array. + free(mFields); + mFields = NULL; + mFieldCountMax = 0; + } + } +#endif ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); }; extern MetaObject g_MetaObject; // Defines "object" behaviour for non-object values. // // RegExMatchObject: Returned by RegExMatch via UnquotedOutputVar. // class RegExMatchObject : public ObjectBase { LPTSTR mHaystack; + int mHaystackStart; int *mOffset; LPTSTR *mPatternName; int mPatternCount; LPTSTR mMark; 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 RegExMatchObject *Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark); ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); #ifdef CONFIG_DEBUGGER void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aDepth); #endif }; // // CriticalObject - Multithread save object wrapper // class CriticalObject : public ObjectBase { protected: IObject *object; LPCRITICAL_SECTION lpCriticalSection; CriticalObject() : lpCriticalSection(0) , object(0) {} bool Delete(); ~CriticalObject(){} public: __int64 GetObj() { return (__int64)&*this->object; } __int64 GetCriSec() { return (__int64) this->lpCriticalSection; } static CriticalObject *Create(ExprTokenType *aParam[], int aParamCount); ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); }; // // Struct - Scriptable associative array. // class Struct : public ObjectBase { protected: typedef INT_PTR IndexType; // Type of index for the internal array. Must be signed for FindKey to work correctly. struct FieldType { UINT_PTR *mStructMem; // Pointer to allocated memory int mSize; // Size of field int mOffset; // Offset for field int mIsPointer; // Pointer depth bool mIsInteger; // IsInteger for NumGet/NumPut bool mIsUnsigned; // IsUnsigned for NumGet/NumPut USHORT mEncoding; // Encoding for StrGet/StrPut int mArraySize; // ArraySize = 0 if not an array int mMemAllocated; // Identify that we allocated memory Var *mVarRef; // Reference to a variable containing the definition LPTSTR key; // Name of field }; FieldType *mFields; IndexType mFieldCount, mFieldCountMax; // Current/max number of fields. // for loop enumerator class Enumerator : public EnumBase { Struct *mObject; IndexType mOffset; public: Enumerator(Struct *aObject) : mObject(aObject), mOffset(-1) { mObject->AddRef(); } ~Enumerator() { mObject->Release(); } int Next(Var *aKey, Var *aVal); }; #ifdef CONFIG_DEBUGGER friend class Debugger; #endif Struct() : mFields(NULL), mFieldCount(0), mFieldCountMax(0), mTypeOnly(false) , mStructMem(0), mSize(0), mIsPointer(0), mIsInteger(true), mIsUnsigned(true) , mEncoding(-1), mArraySize(0), mMemAllocated(false), mVarRef(NULL) {} bool Delete(); ~Struct(); FieldType *FindField(LPTSTR val); FieldType *Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding); bool SetInternalCapacity(IndexType new_capacity); bool Expand() // Expands mFields by at least one field. { return SetInternalCapacity(mFieldCountMax ? mFieldCountMax * 2 : 4); } public: UINT_PTR *mStructMem; // Pointer to allocated memory bool mTypeOnly; // Identify that structure has no fields int mSize; // Size of structure int mIsPointer; // Pointer depth bool mIsInteger; // IsInteger for NumGet/NumPut bool mIsUnsigned; // IsUnsigned for NumGet/NumPut USHORT mEncoding; // Encoding for StrGet/StrPut int mArraySize; // ArraySize = 0 if not an array int mMemAllocated; // Identify that we allocated memory Var *mVarRef; // Reference to a variable containing the definition static Struct *Create(ExprTokenType *aParam[] = NULL, int aParamCount = 0); Struct *Clone(bool aIsDynamic = false); Struct *CloneField(FieldType *field,bool aIsDynamic = false); UINT_PTR SetPointer(UINT_PTR aPointer,int aArrayItem = 1); void ObjectToStruct(IObject *objfrom); ResultType _NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount); ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); #ifdef CONFIG_DEBUGGER void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aDepth); #endif };
tinku99/ahkdll
aec5a2b52b3f171ba19d9805309ec4c59b5545fd
Reverted CriticalSection for ahk[Post]Function
diff --git a/source/AutoHotkey.cpp b/source/AutoHotkey.cpp index d3379b5..c499542 100644 --- a/source/AutoHotkey.cpp +++ b/source/AutoHotkey.cpp @@ -1,345 +1,346 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifndef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "LiteUnzip.h" // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: #ifdef _DEBUG g_hResource = FindResource(NULL, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(NULL, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(NULL, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif g_hInstance = hInstance; InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). + InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; #ifndef AUTOHOTKEYSC /* HotKeyIt start AutoHotkey.ahk in same folder as usual #ifdef _DEBUG TCHAR *script_filespec = _T("Test\\Test.ahk"); #else */ TCHAR *script_filespec = NULL; // Set default as "unspecified/omitted". //#endif #endif // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name. { param = __targv[i]; // For performance and convenience. if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; #ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe). else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= __argc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(__targv[i], TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #endif #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. #ifdef AUTOHOTKEYSC --i; // Make the loop process this item again so that it will be treated as a script param. #else if (!g_hResource) // Only apply if it is not a compiled AutoHotkey.exe script_filespec = param; // The first unrecognized switch must be the script filespec, by design. else --i; // Make the loop process this item again so that it will be treated as a script param. #endif } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); global_init(*g); // Set defaults. // Set up the basics of the script: #ifdef AUTOHOTKEYSC if (g_script.Init(*g, _T(""), restart_mode,0,false) != OK) #else if (g_script.Init(*g, script_filespec, restart_mode,0,false) != OK) // Set up the basics of the script, using the above. #endif return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC UINT load_result = g_script.LoadFromFile(); #else UINT load_result = g_script.LoadFromFile(script_filespec == NULL); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No script was loaded or we're in /iLib mode, so nothing more to do. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(50); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.Break(); } #endif // set exception filter to disable hook before exception occures to avoid system/mouse freeze g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } #endif \ No newline at end of file diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 7e48f30..ee18c9f 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,655 +1,656 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. + InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); g_script.Destroy(); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute || g_Reloading || g_Loading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 diff --git a/source/exports.cpp b/source/exports.cpp index 44d8d45..81ac299 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,1001 +1,1030 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = -1 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); // Following macros are used in addFile addScript ahkExec #ifndef MINIDLL // HotExpr code from LoadFromFile, Hotkeys need to be toggled to get activated #define FINALIZE_HOTKEYS \ if (Hotkey::sHotkeyCount > HotkeyCount)\ {\ Hotstring::SuspendAll(!g_IsSuspended);\ Hotkey::ManifestAllHotkeysHotstringsHooks();\ Hotstring::SuspendAll(g_IsSuspended);\ Hotkey::ManifestAllHotkeysHotstringsHooks();\ } #define RESTORE_IF_EXPR \ for (int expr_line_index = aHotExprLineCount ; expr_line_index < g_HotExprLineCount; ++expr_line_index)\ {\ Line *line = g_HotExprLines[expr_line_index];\ if (!g_script.PreparseBlocks(line))\ return NULL;\ line->mActionType = ACT_IFEXPR;\ }\ g_HotExprLineCount = g_HotExprLineCount + aHotExprLineCount; #endif // AutoHotkey needs to be running at this point #define BACKUP_G_SCRIPT \ int aFuncCount = g_script.mFuncCount;\ int aCurrFileIndex = g_script.mCurrFileIndex, aCombinedLineNumber = g_script.mCombinedLineNumber, aCurrentFuncOpenBlockCount = g_script.mCurrentFuncOpenBlockCount;\ bool aNextLineIsFunctionBody = g_script.mNextLineIsFunctionBody;\ Line *aFirstLine = g_script.mFirstLine,*aLastLine = g_script.mLastLine,*aCurrLine = g_script.mCurrLine,*aFirstStaticLine = g_script.mFirstStaticLine,*aLastStaticLine = g_script.mLastStaticLine;\ g_script.mCurrentFuncOpenBlockCount = NULL;\ g_script.mNextLineIsFunctionBody = false;\ Func *aCurrFunc = g->CurrentFunc;\ int aClassObjectCount = g_script.mClassObjectCount;\ g_script.mClassObjectCount = NULL;\ g_script.mFirstStaticLine = NULL;g_script.mLastStaticLine = NULL;\ g_script.mFirstLine = NULL;g_script.mLastLine = NULL;\ g_script.mIsReadyToExecute = false;\ g->CurrentFunc = NULL; #define RESTORE_G_SCRIPT \ g_script.mFirstLine = aFirstLine;\ g_script.mLastLine = aLastLine;\ g_script.mLastLine->mNextLine = NULL;\ g_script.mCurrLine = aCurrLine;\ g_script.mClassObjectCount = aClassObjectCount + g_script.mClassObjectCount;\ g_script.mCurrFileIndex = aCurrFileIndex;\ g_script.mCurrentFuncOpenBlockCount = aCurrentFuncOpenBlockCount;\ g_script.mNextLineIsFunctionBody = aNextLineIsFunctionBody;\ g_script.mCombinedLineNumber = aCombinedLineNumber; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions int com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} int com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int waitexecute){return addScript(script,waitexecute);} int com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, int waitexecute){return addFile(fileName,waitexecute);} #endif UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} int com_ahkTerminate(int timeout){return ahkTerminate(timeout);} int com_ahkReady(){return ahkReady();} int com_ahkIsUnicode(){return ahkIsUnicode();} int com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif EXPORT int ahkIsUnicode() { #ifdef UNICODE return true; #else return false; #endif } EXPORT int ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); LPTSTR new_mem = (LPTSTR)realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; return ITOA64((int)ahkvar,result_to_return_dll); } if (ahkvar->mType != VAR_BUILTIN && !ahkvar->HasContents() ) return _T(""); if (*ahkvar->mCharContents == '\0') { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_BUILTIN ) { if (ahkvar->mBIV == BIV_IsPaused) { ++g; // imitate new thread for A_IsPaused ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit --g; } else ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteLength + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT int ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamsCount = 0; LPTSTR *params[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; for (;aParamsCount < 10;aParamsCount++) if (!*params[aParamsCount]) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); return -1; } if(aFunc->mIsBuiltIn) { + EnterCriticalSection(&g_CriticalAhkFunction); ResultType aResult = OK; if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; aFuncAndToken.params[i].marker = *params[i]; // Assign parameters } aFuncAndToken.mToken.symbol = SYM_INTEGER; LPTSTR new_buf = (LPTSTR)realloc(aFuncAndToken.buf,MAX_NUMBER_SIZE * sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); + LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.buf = new_buf; aFuncAndToken.mToken.buf = aFuncAndToken.buf; aFuncAndToken.mToken.marker = aFunc->mName; aFunc->mBIF(aResult,aFuncAndToken.mToken,aFuncAndToken.param,aParamsCount); + LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } else { + EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; LPTSTR new_buf; for (int i = 0;(aFunc->mParamCount > i || aFunc->mIsVariadic) && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; new_buf = (LPTSTR)realloc(aFuncAndToken.param[i]->marker,(_tcslen(*params[i])+1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); + LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param[i]->marker = new_buf; _tcscpy(aFuncAndToken.param[i]->marker,*params[i]); // Assign parameters } aFuncAndToken.mFunc = aFunc ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); + LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, int waitexecute) { // dynamically include a file into a script !! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT LPTSTR oldFileSpec = g_script.mFileSpec; g_script.mFileSpec = fileName; if (g_script.LoadFromFile(false)!= OK) //fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g_script.mFileSpec = oldFileSpec; // Restore script path g->CurrentFunc = aCurrFunc; // Restore current function RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; // Set program to be ready for continuing previous script. #ifdef _USRDLL g_Loading = false; #endif return 0; // LOADING_FAILED cant be used due to PTR return type } g_script.mFileSpec = oldFileSpec; #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; // required for return RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int waitexecute) { // dynamically include a script from text!! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif LPCTSTR aPathToShow = g_script.mCurrLine->mArg ? g_script.mCurrLine->mArg->text : g_script.mFileSpec; #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT if (g_script.LoadFromText(script,aPathToShow, false) != OK) // || !g_script.PreparseBlocks(oldLastLine->mNextLine))) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif return 0; // LOADING_FAILED cant be used due to PTR return type } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT int ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type. #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT int aSourceFileIdx = Line::sSourceFileCount; if ((g_script.LoadFromText(script, NULL, false) != OK)) // || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif return NULL; } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; Line *aTempLine = g_script.mLastLine; Line *aExecLine = g_script.mFirstLine; RESTORE_G_SCRIPT g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)aExecLine, (LPARAM)NULL); g_ReturnNotExit = false; Line *prevLine = aTempLine->mPrevLine; for(; prevLine; prevLine = prevLine->mPrevLine) { prevLine->mNextLine->FreeDerefBufIfLarge(); delete prevLine->mNextLine; } for (;Line::sSourceFileCount>aSourceFileIdx;) if (Line::sSourceFile[--Line::sSourceFileCount] != g_script.mOurEXE) free(Line::sSourceFile[Line::sSourceFileCount]); return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamsCount = 0; LPTSTR *params[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; for (;aParamsCount < 10;aParamsCount++) if (!*params[aParamsCount]) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); return _T(""); } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; + EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; aFuncAndToken.params[i].marker = *params[i]; // Assign parameters } aFuncAndToken.mToken.symbol = SYM_INTEGER; LPTSTR new_buf = (LPTSTR)realloc(aFuncAndToken.buf,MAX_NUMBER_SIZE * sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.buf = new_buf; aFuncAndToken.mToken.buf = aFuncAndToken.buf; aFuncAndToken.mToken.marker = aFunc->mName; aFunc->mBIF(aResult,aFuncAndToken.mToken,aFuncAndToken.param,aParamsCount); switch (aFuncAndToken.mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken.mToken.var->Contents())) { new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aFuncAndToken.mToken.var->Contents()) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; _tcscpy(result_to_return_dll,aFuncAndToken.mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken.mToken.marker)) { new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aFuncAndToken.mToken.marker) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; _tcscpy(result_to_return_dll,aFuncAndToken.mToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; ITOA64(aFuncAndToken.mToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken.mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; ITOA64(aFuncAndToken.mToken.value_int64, result_to_return_dll); } + LeaveCriticalSection(&g_CriticalAhkFunction); return result_to_return_dll; } else // UDF { //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); + EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; LPTSTR new_buf; for (int i = 0;(aFunc->mParamCount > i || aFunc->mIsVariadic) && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; new_buf = (LPTSTR)realloc(aFuncAndToken.param[i]->marker,(_tcslen(*params[i])+1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); + LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param[i]->marker = new_buf; _tcscpy(aFuncAndToken.param[i]->marker,*params[i]); // Assign parameters } aFuncAndToken.mFunc = aFunc ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); + LeaveCriticalSection(&g_CriticalAhkFunction); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. //VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. //int var_backup_count; // The number of items in the above array. //if (func.mInstances > 0) // Backup is needed. //if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. // return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); //for (int aParamCount = 0;func.mParamCount > aParamCount && aFuncAndToken->mParamCount > aParamCount;aParamCount++) // func.mParam[aParamCount].var->AssignString(aFuncAndToken->param[aParamCount]); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) ResultType aResult; FuncCallData func_call; // ExprTokenType &aResultToken = aResultToken_to_return ; bool result = func.Call(func_call,aResult,aResultToken,aFuncAndToken->param,(int) aFuncAndToken->mParamCount,false); // Call the UDF. DEBUGGER_STACK_POP() LPTSTR new_buf; if (result) { switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.var->Contents()) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.marker) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } result_to_return_dll = new_buf; sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { VARIANT *variants[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; int aParamsCount = 0; for (;aParamsCount < 10;aParamsCount++) if (variants[aParamsCount]->vt == VT_ERROR) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); VARIANT &r = aFuncAndTokenToReturn[returnCount + 1].variant_to_return_dll; r.vt = VT_NULL ; return r ; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; + EnterCriticalSection(&g_CriticalAhkFunction); ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); if (!aParam) { g_script.ScriptError(ERR_OUTOFMEM,func); VARIANT ret = {}; ret.vt = NULL; + LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aParam[i] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); if (!aParam[i]) { VARIANT ret = {}; ret.vt = NULL; + LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } aParam[i]->symbol = SYM_VAR; aParam[i]->var = (Var*)alloca(sizeof(Var)); if (!aParam[i]->var) { VARIANT ret = {}; ret.vt = NULL; + LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } // prepare variable aParam[i]->var->mType = VAR_NORMAL; aParam[i]->var->mAttrib = 0; aParam[i]->var->mByteCapacity = 0; aParam[i]->var->mHowAllocated = ALLOC_MALLOC; AssignVariant(*aParam[i]->var, *variants[i],false); } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamsCount); // free all variables in case memory was allocated for (int i = 0;i < aParamsCount;i++) aParam[i]->var->Free(); TokenToVariant(aResultToken, variant_to_return_dll); + LeaveCriticalSection(&g_CriticalAhkFunction); return variant_to_return_dll; } else // UDF { + EnterCriticalSection(&g_CriticalAhkFunction); for (int i = 0;aFunc->mParamCount > i;i++) AssignVariant(*aFunc->mParam[i].var, *variants[i],false); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); + LeaveCriticalSection(&g_CriticalAhkFunction); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; + LeaveCriticalSection(&g_CriticalAhkFunction); return r ; } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. //VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. //int var_backup_count; // The number of items in the above array. //if (func.mInstances > 0) // Backup is needed. //if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. //return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/globaldata.cpp b/source/globaldata.cpp index ebf7b39..47013a7 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,555 +1,556 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() // for compiled AutoHotkey.exe #ifdef _USRDLL bool g_Reloading = false; bool g_Loading = false; #endif HINSTANCE g_hInstance = NULL; // Set by WinMain(). HMODULE g_hMemoryModule = NULL; // Set by DllMain() used for COM DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; CRITICAL_SECTION g_CriticalHeapBlocks; +CRITICAL_SECTION g_CriticalAhkFunction; UINT g_DefaultScriptCodepage = CP_ACP; bool g_ReturnNotExit; // for ahkExec/addScript/addFile bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL PVOID g_ExceptionHandler = NULL; SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. static int GetScreenDPI() { // The DPI setting can be different for each screen axis, but // apparently it is such a rare situation that it is not worth // supporting it. So we just retrieve the X axis DPI. HDC hdc = GetDC(NULL); int dpi = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); return dpi; } int g_ScreenDPI = GetScreenDPI(); MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; TCHAR g_default_pwd0; TCHAR g_default_pwd1; TCHAR g_default_pwd2; TCHAR g_default_pwd3; TCHAR g_default_pwd4; TCHAR g_default_pwd5; TCHAR g_default_pwd6; TCHAR g_default_pwd7; TCHAR g_default_pwd8; TCHAR g_default_pwd9; TCHAR *g_default_pwd[] = {&g_default_pwd0,&g_default_pwd1,&g_default_pwd2,&g_default_pwd3,&g_default_pwd4,&g_default_pwd5,&g_default_pwd6,&g_default_pwd7,&g_default_pwd8,&g_default_pwd9,0,0}; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("BreakIf"), 1, 2, 2, {1, 0}} , {_T("Continue"), 0, 1, 1, NULL}, {_T("ContinueIf"), 1, 2, 2, {1, 0}} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("Finally"), 0, 0, 0, NULL} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {_T("IniRead"), 2, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) diff --git a/source/globaldata.h b/source/globaldata.h index d59dabf..6a86878 100644 --- a/source/globaldata.h +++ b/source/globaldata.h @@ -1,371 +1,372 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" #ifdef _USRDLL extern bool g_Reloading; extern bool g_Loading; #endif extern HRSRC g_hResource; // for compiled AutoHotkey.exe extern HINSTANCE g_hInstance; extern HMODULE g_hMemoryModule; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; extern ATOM g_ClassRegistered; extern ATOM g_ClassSplashRegistered; extern CRITICAL_SECTION g_CriticalRegExCache; extern CRITICAL_SECTION g_CriticalHeapBlocks; +extern CRITICAL_SECTION g_CriticalAhkFunction; extern UINT g_DefaultScriptCodepage; extern bool g_ReturnNotExit; // for ahkExec/addScript/addFile 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; #ifndef MINIDLL extern HWND g_hWndSplash; // The SplashText window. extern HFONT g_hFontSplash; #endif extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. 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. #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_HookReceiptOfLControlMeansAltGr; extern DWORD g_IgnoreNextLControlDown; extern DWORD g_IgnoreNextLControlUp; extern BYTE g_MenuMaskKey; // L38: See #MenuMaskKey. // 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_Warn_UseUnsetLocal; extern WarnMode g_Warn_UseUnsetGlobal; extern WarnMode g_Warn_UseEnv; extern WarnMode g_Warn_LocalSameAsGlobal; #ifndef MINIDLL extern PVOID g_ExceptionHandler; extern SingleInstanceType g_AllowOnlyOneInstance; #endif extern bool g_persistent; #ifndef MINIDLL extern bool g_NoTrayIcon; #endif #ifdef AUTOHOTKEYSC extern bool g_AllowMainWindow; #endif extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_AutoExecTimerExists; #ifndef MINIDLL extern bool g_InputTimerExists; #endif extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; #ifndef MINIDLL extern bool g_IsSuspended; #endif extern BOOL g_WriteCacheDisabledInt64; extern BOOL g_WriteCacheDisabledDouble; extern BOOL g_NoEnv; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; #ifndef MINIDLL extern int g_MaxHistoryKeys; #endif extern VarSizeType g_MaxVarCapacity; #ifndef MINIDLL extern UCHAR g_MaxThreadsPerHotkey; #endif extern int g_MaxThreadsTotal; #ifndef MINIDLL extern int g_MaxHotkeysPerInterval; extern int g_HotkeyThrottleInterval; #endif extern bool g_MaxThreadsBuffer; extern SendLevelType g_InputLevel; #ifndef MINIDLL extern HotCriterionType g_HotCriterion; extern LPTSTR g_HotWinTitle; extern LPTSTR g_HotWinText; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #if (expression). See globaldata.cpp for comments. extern int g_HotExprIndex; extern Line **g_HotExprLines; extern int g_HotExprLineCount; extern int g_HotExprLineCountMax; extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern int g_ScreenDPI; extern MenuTypeType g_MenuIsVisible; #endif extern int g_nMessageBoxes; #ifndef MINIDLL extern int g_nInputBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern InputBoxType g_InputBox[MAX_INPUTBOXES]; extern SplashType g_Progress[MAX_PROGRESS_WINDOWS]; extern SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS]; extern GuiType **g_gui; extern int g_guiCount, g_guiCountMax; #endif extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorStruct *g_MsgMonitor; // An array to be allocated upon first use (if any). extern int g_MsgMonitorCount; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern Func *g_SortFunc; extern TCHAR g_delimiter; extern TCHAR g_DerefChar; extern TCHAR g_EscapeChar; #ifndef MINIDLL // 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 bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSSendRaw; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; #endif // Global objects: extern Var *g_ErrorLevel; #ifndef MINIDLL extern input_type g_input; #endif EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; #ifndef MINIDLL extern int g_IconTray; extern int g_IconTraySuspend; #endif extern DWORD g_OriginalTimeout; EXTERN_G; extern global_struct g_default, *g_array; extern TCHAR g_WorkingDir[MAX_PATH]; // Explicit size needed here in .h file for use with sizeof(). extern LPTSTR g_WorkingDirOrig; extern bool g_ContinuationLTrim; 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; #ifndef MINIDLL extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; #endif extern DWORD g_TimeLastInputPhysical; #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE extern bool g_KeyHistoryToFile; #endif #endif // MINIDLL extern TCHAR g_default_pwd0; extern TCHAR g_default_pwd1; extern TCHAR g_default_pwd2; extern TCHAR g_default_pwd3; extern TCHAR g_default_pwd4; extern TCHAR g_default_pwd5; extern TCHAR g_default_pwd6; extern TCHAR g_default_pwd7; extern TCHAR g_default_pwd8; extern TCHAR g_default_pwd9; extern TCHAR *g_default_pwd[]; // 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. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ if (!g_AutoExecTimerExists)\ g_AutoExecTimerExists = SetTimer(g_hWnd, TIMER_ID_AUTOEXEC, aTimeoutValue, AutoExecSectionTimeout);\ } // v1.0.39 for above: Removed the call to ExitApp() upon failure. See SET_MAIN_TIMER for details. #ifndef MINIDLL #define SET_INPUT_TIMER(aTimeoutValue) \ if (!g_InputTimerExists)\ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); #endif // 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; // See above comment about g->AllowThreadToBeInterrupted. #define KILL_AUTOEXEC_TIMER \ {\ if (g_AutoExecTimerExists && KillTimer(g_hWnd, TIMER_ID_AUTOEXEC))\ g_AutoExecTimerExists = false;\ } #ifndef MINIDLL #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #endif #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif
tinku99/ahkdll
db57b663be4bf9859da598a9e1d79b2e1b376851
Removed deletion of CriticalSection when CriticalObject is deleted
diff --git a/source/script2.cpp b/source/script2.cpp index 99bc090..453364f 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -14312,1055 +14312,1050 @@ BIF_DECL(BIF_DllCall) #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj; if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; CriticalObject *criticalref = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (obj = TokenToObject(*aParam[0])) { if (criticalref = dynamic_cast<CriticalObject *>(obj)) obj = (IObject *)criticalref->GetObj(); obj->AddRef(); } else if (obj = (IObject *)TokenToInt64(*aParam[0])) { if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) { obj = (IObject *)criticalref->GetObj(); obj->AddRef(); } else obj->AddRef(); } if (!obj) { g_script.ScriptError(aParamCount == 0 ? ERR_OUTOFMEM : ERR_PARAM1_INVALID ); return NULL; } // create new critical object CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (criticalref) criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)criticalref->GetCriSec(); else if (aParamCount < 2) { // no Critical Section reference was given, create one - criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); + criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)GlobalAlloc(0, sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) // Check if we own the critical section and release it while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); - ULONG refcount = this->object->Release(); + this->object->Release(); LeaveCriticalSection(this->lpCriticalSection); - if (refcount == 0) - { - DeleteCriticalSection((LPCRITICAL_SECTION)this->GetCriSec()); - free(this->lpCriticalSection); - } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = ParamIndexToString(0, haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)ParamIndexLength(0, haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)ParamIndexToInt64(1) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)ParamIndexToInt64(2)) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = ParamIndexToString(0, aResultToken.buf); LPTSTR needle = ParamIndexToString(1, needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(!ParamIndexIsOmitted(2) && ParamIndexToInt64(2)); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = ParamIndexToOptionalInt(4, 1); if (!ParamIndexIsOmitted(3)) // There is a starting position present. { offset = ParamIndexToIntPtr(3); // i.e. the fourth arg. // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = ParamIndexLength(0, haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? ParamIndexLength(1, needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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. return m; } ResultType STDMETHODCALLTYPE RegExMatchObject::Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) { if (aParamCount < 1 || aParamCount > 2 || IS_INVOKE_SET) return INVOKE_NOT_HANDLED; LPTSTR name; int p = -1; // Check for a subpattern offset/name first so that a subpattern named "Pos" takes // precedence over our "Pos" property when invoked like m.Pos (but not m.Pos()). if (aParamCount > 1 || !IS_INVOKE_CALL) { ExprTokenType &name_param = *aParam[aParamCount - 1]; if (TokenIsPureNumeric(name_param)) { p = (int)TokenToInt64(name_param, TRUE); } else if (mPatternName) // i.e. there is at least one named subpattern. { name = TokenToString(name_param); 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; } } } bool pattern_found = p >= 0 && p < mPatternCount; // Checked for named properties: if (aParamCount > 1 || !pattern_found) { name = TokenToString(*aParam[0]); if (!pattern_found && aParamCount == 1) { p = 0; // For m.Pos, m.Len and m.Value, use the overall match. pattern_found = true; // Relies on below returning if the property name is invalid. } if (!_tcsicmp(name, _T("Pos"))) { if (pattern_found) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = mOffset[2*p] + 1; } return OK;
tinku99/ahkdll
d43b223b7365f4ee1d0150adf627ea3a5e2184c1
Fixed creation of CriticalObject
diff --git a/source/script2.cpp b/source/script2.cpp index b7ad5eb..99bc090 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -14274,1049 +14274,1053 @@ BIF_DECL(BIF_DllCall) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. break; case SYM_STRING: case SYM_OPERAND: return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. break; default: return_type_string[0] = _T(""); // It will be detected as invalid below. return_type_string[1] = NULL; break; } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj; if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } + CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; CriticalObject *criticalref = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); - else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) + else if (obj = TokenToObject(*aParam[0])) { - obj = (IObject *)TokenToInt64(*aParam[0]); // object reference + if (criticalref = dynamic_cast<CriticalObject *>(obj)) + obj = (IObject *)criticalref->GetObj(); + obj->AddRef(); + } + else if (obj = (IObject *)TokenToInt64(*aParam[0])) + { if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) + { obj = (IObject *)criticalref->GetObj(); - if (obj) + obj->AddRef(); + } + else obj->AddRef(); } - - if (!obj) // Check if it is an object or var containing object - { - obj = TokenToObject(*aParam[0]); - if (obj < (IObject *)1024) // Prevent some obvious errors. - return 0; - else if (criticalref = dynamic_cast<CriticalObject *>(obj)) - obj = (IObject *)criticalref->GetObj(); - obj->AddRef(); + if (!obj) + { + g_script.ScriptError(aParamCount == 0 ? ERR_OUTOFMEM : ERR_PARAM1_INVALID ); + return NULL; } // create new critical object CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (criticalref) criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)criticalref->GetCriSec(); else if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) // Check if we own the critical section and release it while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); ULONG refcount = this->object->Release(); LeaveCriticalSection(this->lpCriticalSection); if (refcount == 0) { DeleteCriticalSection((LPCRITICAL_SECTION)this->GetCriSec()); free(this->lpCriticalSection); } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = ParamIndexToString(0, haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)ParamIndexLength(0, haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)ParamIndexToInt64(1) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)ParamIndexToInt64(2)) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = ParamIndexToString(0, aResultToken.buf); LPTSTR needle = ParamIndexToString(1, needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(!ParamIndexIsOmitted(2) && ParamIndexToInt64(2)); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = ParamIndexToOptionalInt(4, 1); if (!ParamIndexIsOmitted(3)) // There is a starting position present. { offset = ParamIndexToIntPtr(3); // i.e. the fourth arg. // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = ParamIndexLength(0, haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? ParamIndexLength(1, needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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. return m; } ResultType STDMETHODCALLTYPE RegExMatchObject::Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) { if (aParamCount < 1 || aParamCount > 2 || IS_INVOKE_SET) return INVOKE_NOT_HANDLED; LPTSTR name; int p = -1; // Check for a subpattern offset/name first so that a subpattern named "Pos" takes // precedence over our "Pos" property when invoked like m.Pos (but not m.Pos()). if (aParamCount > 1 || !IS_INVOKE_CALL) { ExprTokenType &name_param = *aParam[aParamCount - 1]; if (TokenIsPureNumeric(name_param)) { p = (int)TokenToInt64(name_param, TRUE); } else if (mPatternName) // i.e. there is at least one named subpattern. {
tinku99/ahkdll
76dae37a7dbc1b072fbfcb90b8995fd147ba78f0
Fixed creation of CriticalObject
diff --git a/source/script2.cpp b/source/script2.cpp index 5b5f1c3..b7ad5eb 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -14287,1025 +14287,1026 @@ BIF_DECL(BIF_DllCall) break; } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj; if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; CriticalObject *criticalref = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) obj = (IObject *)criticalref->GetObj(); - obj->AddRef(); + if (obj) + obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) obj = (IObject *)criticalref->GetObj(); obj->AddRef(); } // create new critical object CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (criticalref) criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)criticalref->GetCriSec(); else if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) // Check if we own the critical section and release it while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); ULONG refcount = this->object->Release(); LeaveCriticalSection(this->lpCriticalSection); if (refcount == 0) { DeleteCriticalSection((LPCRITICAL_SECTION)this->GetCriSec()); free(this->lpCriticalSection); } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = ParamIndexToString(0, haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)ParamIndexLength(0, haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)ParamIndexToInt64(1) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)ParamIndexToInt64(2)) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = ParamIndexToString(0, aResultToken.buf); LPTSTR needle = ParamIndexToString(1, needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(!ParamIndexIsOmitted(2) && ParamIndexToInt64(2)); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = ParamIndexToOptionalInt(4, 1); if (!ParamIndexIsOmitted(3)) // There is a starting position present. { offset = ParamIndexToIntPtr(3); // i.e. the fourth arg. // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = ParamIndexLength(0, haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? ParamIndexLength(1, needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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. return m; } ResultType STDMETHODCALLTYPE RegExMatchObject::Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) { if (aParamCount < 1 || aParamCount > 2 || IS_INVOKE_SET) return INVOKE_NOT_HANDLED; LPTSTR name; int p = -1; // Check for a subpattern offset/name first so that a subpattern named "Pos" takes // precedence over our "Pos" property when invoked like m.Pos (but not m.Pos()).
tinku99/ahkdll
7d219f7c693115dd19e954aef99e6b3f51569c97
Fixed deletion of CriticalObject
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 538a05b..ee18c9f 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,987 +1,989 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif + + g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. + Sleep(20); + g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); - Sleep(20); - g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. - g_Reloading = false; + // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); g_script.Destroy(); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute || g_Reloading || g_Loading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) { if (IsUnicode==NULL) return ERROR_INVALID_PARAMETER; *IsUnicode = com_ahkIsUnicode(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) { // search for TypeLib in current dll WCHAR buf[MAX_PATH * sizeof(WCHAR)]; // LoadTypeLibEx needs Unicode string if (GetModuleFileNameW(g_hInstance, buf, _countof(buf))) hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); else // MemoryModule, search troug g_ListOfMemoryModules and use temp file to extract and load TypeLib file { HMEMORYMODULE hmodule = (HMEMORYMODULE)(g_hMemoryModule); HMEMORYRSRC res = MemoryFindResource(hmodule,_T("TYPELIB"),MAKEINTRESOURCE(1)); if (!res) return TYPE_E_INVALIDSTATE; DWORD resSize = MemorySizeOfResource(hmodule,res); // Path to temp directory + our temporary file name DWORD tempPathLength = GetTempPathW(MAX_PATH, buf); wcscpy(buf + tempPathLength,L"AutoHotkey.MemoryModule.temp.tlb"); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after LoadTypeLib has been called. HANDLE hFile = CreateFileW(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,MemoryLoadResource(hmodule,res),resSize,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to write data, continue and try loading } hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileW(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); } if (FAILED(hr)) return hr; } diff --git a/source/script2.cpp b/source/script2.cpp index 5786107..5b5f1c3 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -14323,1030 +14323,1034 @@ BIF_DECL(BIF_DllCall) return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj; if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; CriticalObject *criticalref = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) obj = (IObject *)criticalref->GetObj(); obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else if (criticalref = dynamic_cast<CriticalObject *>(obj)) obj = (IObject *)criticalref->GetObj(); obj->AddRef(); } // create new critical object CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (criticalref) criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)criticalref->GetCriSec(); else if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { + // Avoid deadlocking the process so messages can still be processed + DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) // Check if we own the critical section and release it - if (TryEnterCriticalSection(this->lpCriticalSection)) - { - LeaveCriticalSection(this->lpCriticalSection); - } + while (!TryEnterCriticalSection(this->lpCriticalSection)) + if (g_MainThreadID == aThreadID) + MsgSleep(-1); + else + Sleep(0); ULONG refcount = this->object->Release(); + LeaveCriticalSection(this->lpCriticalSection); if (refcount == 0) { DeleteCriticalSection((LPCRITICAL_SECTION)this->GetCriSec()); free(this->lpCriticalSection); } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = ParamIndexToString(0, haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)ParamIndexLength(0, haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)ParamIndexToInt64(1) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)ParamIndexToInt64(2)) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = ParamIndexToString(0, aResultToken.buf); LPTSTR needle = ParamIndexToString(1, needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(!ParamIndexIsOmitted(2) && ParamIndexToInt64(2)); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = ParamIndexToOptionalInt(4, 1); if (!ParamIndexIsOmitted(3)) // There is a starting position present. { offset = ParamIndexToIntPtr(3); // i.e. the fourth arg. // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = ParamIndexLength(0, haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? ParamIndexLength(1, needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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. return m; } ResultType STDMETHODCALLTYPE RegExMatchObject::Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) { if (aParamCount < 1 || aParamCount > 2 || IS_INVOKE_SET) return INVOKE_NOT_HANDLED; LPTSTR name; int p = -1; // Check for a subpattern offset/name first so that a subpattern named "Pos" takes // precedence over our "Pos" property when invoked like m.Pos (but not m.Pos()). if (aParamCount > 1 || !IS_INVOKE_CALL) { ExprTokenType &name_param = *aParam[aParamCount - 1]; if (TokenIsPureNumeric(name_param)) { p = (int)TokenToInt64(name_param, TRUE); } else if (mPatternName) // i.e. there is at least one named subpattern. { name = TokenToString(name_param); 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; } } } bool pattern_found = p >= 0 && p < mPatternCount; // Checked for named properties: if (aParamCount > 1 || !pattern_found) { name = TokenToString(*aParam[0]); if (!pattern_found && aParamCount == 1) { p = 0; // For m.Pos, m.Len and m.Value, use the overall match. pattern_found = true; // Relies on below returning if the property name is invalid. } if (!_tcsicmp(name, _T("Pos"))) { if (pattern_found)
tinku99/ahkdll
cdafe0a39fa2a3cb4484ab0058bc3e653d85f1d2
Fix for hotkeys added via addFile and addScript
diff --git a/source/exports.cpp b/source/exports.cpp index e55d024..81ac299 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,531 +1,534 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = -1 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); // Following macros are used in addFile addScript ahkExec #ifndef MINIDLL // HotExpr code from LoadFromFile, Hotkeys need to be toggled to get activated #define FINALIZE_HOTKEYS \ if (Hotkey::sHotkeyCount > HotkeyCount)\ {\ + Hotstring::SuspendAll(!g_IsSuspended);\ + Hotkey::ManifestAllHotkeysHotstringsHooks();\ + Hotstring::SuspendAll(g_IsSuspended);\ Hotkey::ManifestAllHotkeysHotstringsHooks();\ } #define RESTORE_IF_EXPR \ for (int expr_line_index = aHotExprLineCount ; expr_line_index < g_HotExprLineCount; ++expr_line_index)\ {\ Line *line = g_HotExprLines[expr_line_index];\ if (!g_script.PreparseBlocks(line))\ return NULL;\ line->mActionType = ACT_IFEXPR;\ }\ g_HotExprLineCount = g_HotExprLineCount + aHotExprLineCount; #endif // AutoHotkey needs to be running at this point #define BACKUP_G_SCRIPT \ int aFuncCount = g_script.mFuncCount;\ int aCurrFileIndex = g_script.mCurrFileIndex, aCombinedLineNumber = g_script.mCombinedLineNumber, aCurrentFuncOpenBlockCount = g_script.mCurrentFuncOpenBlockCount;\ bool aNextLineIsFunctionBody = g_script.mNextLineIsFunctionBody;\ Line *aFirstLine = g_script.mFirstLine,*aLastLine = g_script.mLastLine,*aCurrLine = g_script.mCurrLine,*aFirstStaticLine = g_script.mFirstStaticLine,*aLastStaticLine = g_script.mLastStaticLine;\ g_script.mCurrentFuncOpenBlockCount = NULL;\ g_script.mNextLineIsFunctionBody = false;\ Func *aCurrFunc = g->CurrentFunc;\ int aClassObjectCount = g_script.mClassObjectCount;\ g_script.mClassObjectCount = NULL;\ g_script.mFirstStaticLine = NULL;g_script.mLastStaticLine = NULL;\ g_script.mFirstLine = NULL;g_script.mLastLine = NULL;\ g_script.mIsReadyToExecute = false;\ g->CurrentFunc = NULL; #define RESTORE_G_SCRIPT \ g_script.mFirstLine = aFirstLine;\ g_script.mLastLine = aLastLine;\ g_script.mLastLine->mNextLine = NULL;\ g_script.mCurrLine = aCurrLine;\ g_script.mClassObjectCount = aClassObjectCount + g_script.mClassObjectCount;\ g_script.mCurrFileIndex = aCurrFileIndex;\ g_script.mCurrentFuncOpenBlockCount = aCurrentFuncOpenBlockCount;\ g_script.mNextLineIsFunctionBody = aNextLineIsFunctionBody;\ g_script.mCombinedLineNumber = aCombinedLineNumber; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions int com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} int com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int waitexecute){return addScript(script,waitexecute);} int com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, int waitexecute){return addFile(fileName,waitexecute);} #endif UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} int com_ahkTerminate(int timeout){return ahkTerminate(timeout);} int com_ahkReady(){return ahkReady();} int com_ahkIsUnicode(){return ahkIsUnicode();} int com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif EXPORT int ahkIsUnicode() { #ifdef UNICODE return true; #else return false; #endif } EXPORT int ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); LPTSTR new_mem = (LPTSTR)realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; return ITOA64((int)ahkvar,result_to_return_dll); } if (ahkvar->mType != VAR_BUILTIN && !ahkvar->HasContents() ) return _T(""); if (*ahkvar->mCharContents == '\0') { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_BUILTIN ) { if (ahkvar->mBIV == BIV_IsPaused) { ++g; // imitate new thread for A_IsPaused ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit --g; } else ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteLength + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT int ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamsCount = 0; LPTSTR *params[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; for (;aParamsCount < 10;aParamsCount++) if (!*params[aParamsCount]) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); return -1; } if(aFunc->mIsBuiltIn) { EnterCriticalSection(&g_CriticalAhkFunction); ResultType aResult = OK; if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; aFuncAndToken.params[i].marker = *params[i]; // Assign parameters } aFuncAndToken.mToken.symbol = SYM_INTEGER; LPTSTR new_buf = (LPTSTR)realloc(aFuncAndToken.buf,MAX_NUMBER_SIZE * sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.buf = new_buf; aFuncAndToken.mToken.buf = aFuncAndToken.buf; aFuncAndToken.mToken.marker = aFunc->mName; aFunc->mBIF(aResult,aFuncAndToken.mToken,aFuncAndToken.param,aParamsCount); LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } else { EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; LPTSTR new_buf; for (int i = 0;(aFunc->mParamCount > i || aFunc->mIsVariadic) && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; new_buf = (LPTSTR)realloc(aFuncAndToken.param[i]->marker,(_tcslen(*params[i])+1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param[i]->marker = new_buf; _tcscpy(aFuncAndToken.param[i]->marker,*params[i]); // Assign parameters } aFuncAndToken.mFunc = aFunc ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, int waitexecute) { // dynamically include a file into a script !! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT LPTSTR oldFileSpec = g_script.mFileSpec; g_script.mFileSpec = fileName; if (g_script.LoadFromFile(false)!= OK) //fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g_script.mFileSpec = oldFileSpec; // Restore script path g->CurrentFunc = aCurrFunc; // Restore current function RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; // Set program to be ready for continuing previous script. #ifdef _USRDLL g_Loading = false; #endif return 0; // LOADING_FAILED cant be used due to PTR return type } g_script.mFileSpec = oldFileSpec; #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; // required for return RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int waitexecute) { // dynamically include a script from text!! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif LPCTSTR aPathToShow = g_script.mCurrLine->mArg ? g_script.mCurrLine->mArg->text : g_script.mFileSpec; #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT if (g_script.LoadFromText(script,aPathToShow, false) != OK) // || !g_script.PreparseBlocks(oldLastLine->mNextLine))) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif return 0; // LOADING_FAILED cant be used due to PTR return type } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT int ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type. #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif #ifdef _USRDLL g_Loading = true; #endif BACKUP_G_SCRIPT int aSourceFileIdx = Line::sSourceFileCount; if ((g_script.LoadFromText(script, NULL, false) != OK)) // || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif return NULL; } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; #ifdef _USRDLL g_Loading = false; #endif g->CurrentFunc = aCurrFunc; Line *aTempLine = g_script.mLastLine; Line *aExecLine = g_script.mFirstLine; RESTORE_G_SCRIPT g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)aExecLine, (LPARAM)NULL); g_ReturnNotExit = false; Line *prevLine = aTempLine->mPrevLine;
tinku99/ahkdll
f1d1ad2b7794c4410add4f5381ae9be2885d5d41
Allow to init CriticalObject from another CriticalObject and use its CriticalSection, also CriticalSection is deleted when last object reference is removed
diff --git a/source/script2.cpp b/source/script2.cpp index 2bbcb35..5786107 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -14277,1071 +14277,1081 @@ BIF_DECL(BIF_DllCall) return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. break; case SYM_STRING: case SYM_OPERAND: return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. break; default: return_type_string[0] = _T(""); // It will be detected as invalid below. return_type_string[1] = NULL; break; } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj; if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; + CriticalObject *criticalref = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; - else - obj->AddRef(); + else if (criticalref = dynamic_cast<CriticalObject *>(obj)) + obj = (IObject *)criticalref->GetObj(); + obj->AddRef(); } + if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; - else - obj->AddRef(); + else if (criticalref = dynamic_cast<CriticalObject *>(obj)) + obj = (IObject *)criticalref->GetObj(); + obj->AddRef(); } - - // create new critical object and save reference + // create new critical object CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; - if (aParamCount < 2) + if (criticalref) + criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)criticalref->GetCriSec(); + else if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Check if we own the critical section and release it if (TryEnterCriticalSection(this->lpCriticalSection)) { LeaveCriticalSection(this->lpCriticalSection); } - this->object->Release(); + ULONG refcount = this->object->Release(); + if (refcount == 0) + { + DeleteCriticalSection((LPCRITICAL_SECTION)this->GetCriSec()); + free(this->lpCriticalSection); + } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed DWORD aThreadID = GetCurrentThreadId(); // Used to identify if code is called from different thread (AutoHotkey.dll) while (!TryEnterCriticalSection(this->lpCriticalSection)) if (g_MainThreadID == aThreadID) MsgSleep(-1); else Sleep(0); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = ParamIndexToString(0, haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)ParamIndexLength(0, haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)ParamIndexToInt64(1) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)ParamIndexToInt64(2)) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = ParamIndexToString(0, aResultToken.buf); LPTSTR needle = ParamIndexToString(1, needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(!ParamIndexIsOmitted(2) && ParamIndexToInt64(2)); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = ParamIndexToOptionalInt(4, 1); if (!ParamIndexIsOmitted(3)) // There is a starting position present. { offset = ParamIndexToIntPtr(3); // i.e. the fourth arg. // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = ParamIndexLength(0, haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? ParamIndexLength(1, needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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. return m; } ResultType STDMETHODCALLTYPE RegExMatchObject::Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) { if (aParamCount < 1 || aParamCount > 2 || IS_INVOKE_SET) return INVOKE_NOT_HANDLED; LPTSTR name; int p = -1; // Check for a subpattern offset/name first so that a subpattern named "Pos" takes // precedence over our "Pos" property when invoked like m.Pos (but not m.Pos()). if (aParamCount > 1 || !IS_INVOKE_CALL) { ExprTokenType &name_param = *aParam[aParamCount - 1]; if (TokenIsPureNumeric(name_param)) { p = (int)TokenToInt64(name_param, TRUE); } else if (mPatternName) // i.e. there is at least one named subpattern. { name = TokenToString(name_param); 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; } } } bool pattern_found = p >= 0 && p < mPatternCount; // Checked for named properties: if (aParamCount > 1 || !pattern_found) { name = TokenToString(*aParam[0]); if (!pattern_found && aParamCount == 1) { p = 0; // For m.Pos, m.Len and m.Value, use the overall match. pattern_found = true; // Relies on below returning if the property name is invalid. } if (!_tcsicmp(name, _T("Pos"))) { if (pattern_found) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = mOffset[2*p] + 1; } return OK;
tinku99/ahkdll
ab8cc54c315a0f21ae44613432e3600b6c0a9397
Fixed ahkReady when ahkExec, addFile or addScript is executed
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 6b921d3..538a05b 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,1133 +1,1133 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif #ifndef MINIDLL // set exception filter to disable hook before exception occures to avoid system/mouse freeze // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif - g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. - Sleep(20); - g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); + Sleep(20); + g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. + g_Reloading = false; // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); g_script.Destroy(); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { - return g_script.mIsReadyToExecute ||g_Reloading; + return g_script.mIsReadyToExecute || g_Reloading || g_Loading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) { if (IsUnicode==NULL) return ERROR_INVALID_PARAMETER; *IsUnicode = com_ahkIsUnicode(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) { // search for TypeLib in current dll WCHAR buf[MAX_PATH * sizeof(WCHAR)]; // LoadTypeLibEx needs Unicode string if (GetModuleFileNameW(g_hInstance, buf, _countof(buf))) hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); else // MemoryModule, search troug g_ListOfMemoryModules and use temp file to extract and load TypeLib file { HMEMORYMODULE hmodule = (HMEMORYMODULE)(g_hMemoryModule); HMEMORYRSRC res = MemoryFindResource(hmodule,_T("TYPELIB"),MAKEINTRESOURCE(1)); if (!res) return TYPE_E_INVALIDSTATE; DWORD resSize = MemorySizeOfResource(hmodule,res); // Path to temp directory + our temporary file name DWORD tempPathLength = GetTempPathW(MAX_PATH, buf); wcscpy(buf + tempPathLength,L"AutoHotkey.MemoryModule.temp.tlb"); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after LoadTypeLib has been called. HANDLE hFile = CreateFileW(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,MemoryLoadResource(hmodule,res),resSize,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to write data, continue and try loading } hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileW(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); } if (FAILED(hr)) return hr; } // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; diff --git a/source/exports.cpp b/source/exports.cpp index 41b93b5..e55d024 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,1001 +1,1027 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = -1 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); // Following macros are used in addFile addScript ahkExec #ifndef MINIDLL // HotExpr code from LoadFromFile, Hotkeys need to be toggled to get activated #define FINALIZE_HOTKEYS \ if (Hotkey::sHotkeyCount > HotkeyCount)\ {\ - Line::ToggleSuspendState();\ - Line::ToggleSuspendState();\ + Hotkey::ManifestAllHotkeysHotstringsHooks();\ } #define RESTORE_IF_EXPR \ for (int expr_line_index = aHotExprLineCount ; expr_line_index < g_HotExprLineCount; ++expr_line_index)\ {\ Line *line = g_HotExprLines[expr_line_index];\ if (!g_script.PreparseBlocks(line))\ return NULL;\ line->mActionType = ACT_IFEXPR;\ }\ g_HotExprLineCount = g_HotExprLineCount + aHotExprLineCount; #endif // AutoHotkey needs to be running at this point #define BACKUP_G_SCRIPT \ int aFuncCount = g_script.mFuncCount;\ int aCurrFileIndex = g_script.mCurrFileIndex, aCombinedLineNumber = g_script.mCombinedLineNumber, aCurrentFuncOpenBlockCount = g_script.mCurrentFuncOpenBlockCount;\ bool aNextLineIsFunctionBody = g_script.mNextLineIsFunctionBody;\ Line *aFirstLine = g_script.mFirstLine,*aLastLine = g_script.mLastLine,*aCurrLine = g_script.mCurrLine,*aFirstStaticLine = g_script.mFirstStaticLine,*aLastStaticLine = g_script.mLastStaticLine;\ g_script.mCurrentFuncOpenBlockCount = NULL;\ g_script.mNextLineIsFunctionBody = false;\ Func *aCurrFunc = g->CurrentFunc;\ int aClassObjectCount = g_script.mClassObjectCount;\ g_script.mClassObjectCount = NULL;\ g_script.mFirstStaticLine = NULL;g_script.mLastStaticLine = NULL;\ g_script.mFirstLine = NULL;g_script.mLastLine = NULL;\ g_script.mIsReadyToExecute = false;\ g->CurrentFunc = NULL; #define RESTORE_G_SCRIPT \ g_script.mFirstLine = aFirstLine;\ g_script.mLastLine = aLastLine;\ g_script.mLastLine->mNextLine = NULL;\ g_script.mCurrLine = aCurrLine;\ g_script.mClassObjectCount = aClassObjectCount + g_script.mClassObjectCount;\ g_script.mCurrFileIndex = aCurrFileIndex;\ g_script.mCurrentFuncOpenBlockCount = aCurrentFuncOpenBlockCount;\ g_script.mNextLineIsFunctionBody = aNextLineIsFunctionBody;\ g_script.mCombinedLineNumber = aCombinedLineNumber; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions int com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} int com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int waitexecute){return addScript(script,waitexecute);} int com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, int waitexecute){return addFile(fileName,waitexecute);} #endif UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} int com_ahkTerminate(int timeout){return ahkTerminate(timeout);} int com_ahkReady(){return ahkReady();} int com_ahkIsUnicode(){return ahkIsUnicode();} int com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif EXPORT int ahkIsUnicode() { #ifdef UNICODE return true; #else return false; #endif } EXPORT int ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); LPTSTR new_mem = (LPTSTR)realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; return ITOA64((int)ahkvar,result_to_return_dll); } if (ahkvar->mType != VAR_BUILTIN && !ahkvar->HasContents() ) return _T(""); if (*ahkvar->mCharContents == '\0') { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_BUILTIN ) { if (ahkvar->mBIV == BIV_IsPaused) { ++g; // imitate new thread for A_IsPaused ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit --g; } else ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { LPTSTR new_mem = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mType == VAR_BUILTIN ? ahkvar->mBIV(0,name) : ahkvar->mByteLength + sizeof(TCHAR)); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM, name); return _T(""); } result_to_return_dll = new_mem; if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT int ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamsCount = 0; LPTSTR *params[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; for (;aParamsCount < 10;aParamsCount++) if (!*params[aParamsCount]) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); return -1; } if(aFunc->mIsBuiltIn) { EnterCriticalSection(&g_CriticalAhkFunction); ResultType aResult = OK; if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; aFuncAndToken.params[i].marker = *params[i]; // Assign parameters } aFuncAndToken.mToken.symbol = SYM_INTEGER; LPTSTR new_buf = (LPTSTR)realloc(aFuncAndToken.buf,MAX_NUMBER_SIZE * sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.buf = new_buf; aFuncAndToken.mToken.buf = aFuncAndToken.buf; aFuncAndToken.mToken.marker = aFunc->mName; aFunc->mBIF(aResult,aFuncAndToken.mToken,aFuncAndToken.param,aParamsCount); LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } else { EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; LPTSTR new_buf; for (int i = 0;(aFunc->mParamCount > i || aFunc->mIsVariadic) && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; new_buf = (LPTSTR)realloc(aFuncAndToken.param[i]->marker,(_tcslen(*params[i])+1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM, func); LeaveCriticalSection(&g_CriticalAhkFunction); return -1; } aFuncAndToken.param[i]->marker = new_buf; _tcscpy(aFuncAndToken.param[i]->marker,*params[i]); // Assign parameters } aFuncAndToken.mFunc = aFunc ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); LeaveCriticalSection(&g_CriticalAhkFunction); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, int waitexecute) { // dynamically include a file into a script !! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; +#endif +#ifdef _USRDLL + g_Loading = true; #endif BACKUP_G_SCRIPT LPTSTR oldFileSpec = g_script.mFileSpec; g_script.mFileSpec = fileName; if (g_script.LoadFromFile(false)!= OK) //fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g_script.mFileSpec = oldFileSpec; // Restore script path g->CurrentFunc = aCurrFunc; // Restore current function RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; // Set program to be ready for continuing previous script. +#ifdef _USRDLL + g_Loading = false; +#endif return 0; // LOADING_FAILED cant be used due to PTR return type } g_script.mFileSpec = oldFileSpec; #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; +#ifdef _USRDLL + g_Loading = false; +#endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; // required for return RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int waitexecute) { // dynamically include a script from text!! // labels, hotkeys, functions. if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; #endif LPCTSTR aPathToShow = g_script.mCurrLine->mArg ? g_script.mCurrLine->mArg->text : g_script.mFileSpec; +#ifdef _USRDLL + g_Loading = true; +#endif BACKUP_G_SCRIPT if (g_script.LoadFromText(script,aPathToShow, false) != OK) // || !g_script.PreparseBlocks(oldLastLine->mNextLine))) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; +#ifdef _USRDLL + g_Loading = false; +#endif return 0; // LOADING_FAILED cant be used due to PTR return type } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; +#ifdef _USRDLL + g_Loading = false; +#endif g->CurrentFunc = aCurrFunc; if (waitexecute != 0) { if (waitexecute == 1) { g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); g_ReturnNotExit = false; } else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)NULL); } else { // Static init lines need always to run Line *tempstatic = NULL; while (tempstatic != g_script.mLastStaticLine) { if (tempstatic == NULL) tempstatic = g_script.mFirstStaticLine; else tempstatic = tempstatic->mNextLine; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)tempstatic, (LPARAM)ONLY_ONE_LINE); } } Line *aTempLine = g_script.mFirstLine; RESTORE_G_SCRIPT return (UINT_PTR) aTempLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT int ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions if (!g_script.mIsReadyToExecute) return 0; // AutoHotkey needs to be running at this point // LOADING_FAILED cant be used due to PTR return type. #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; int aHotExprLineCount = g_HotExprLineCount; +#endif +#ifdef _USRDLL + g_Loading = true; #endif BACKUP_G_SCRIPT int aSourceFileIdx = Line::sSourceFileCount; if ((g_script.LoadFromText(script, NULL, false) != OK)) // || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { g->CurrentFunc = aCurrFunc; RESTORE_G_SCRIPT #ifndef MINIDLL RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; +#ifdef _USRDLL + g_Loading = false; +#endif return NULL; } #ifndef MINIDLL FINALIZE_HOTKEYS RESTORE_IF_EXPR #endif g_script.mIsReadyToExecute = true; +#ifdef _USRDLL + g_Loading = false; +#endif g->CurrentFunc = aCurrFunc; Line *aTempLine = g_script.mLastLine; Line *aExecLine = g_script.mFirstLine; RESTORE_G_SCRIPT g_ReturnNotExit = true; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)aExecLine, (LPARAM)NULL); g_ReturnNotExit = false; Line *prevLine = aTempLine->mPrevLine; for(; prevLine; prevLine = prevLine->mPrevLine) { prevLine->mNextLine->FreeDerefBufIfLarge(); delete prevLine->mNextLine; } for (;Line::sSourceFileCount>aSourceFileIdx;) if (Line::sSourceFile[--Line::sSourceFileCount] != g_script.mOurEXE) free(Line::sSourceFile[Line::sSourceFileCount]); return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamsCount = 0; LPTSTR *params[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; for (;aParamsCount < 10;aParamsCount++) if (!*params[aParamsCount]) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); return _T(""); } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; aFuncAndToken.params[i].marker = *params[i]; // Assign parameters } aFuncAndToken.mToken.symbol = SYM_INTEGER; LPTSTR new_buf = (LPTSTR)realloc(aFuncAndToken.buf,MAX_NUMBER_SIZE * sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.buf = new_buf; aFuncAndToken.mToken.buf = aFuncAndToken.buf; aFuncAndToken.mToken.marker = aFunc->mName; aFunc->mBIF(aResult,aFuncAndToken.mToken,aFuncAndToken.param,aParamsCount); switch (aFuncAndToken.mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken.mToken.var->Contents())) { new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aFuncAndToken.mToken.var->Contents()) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; _tcscpy(result_to_return_dll,aFuncAndToken.mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken.mToken.marker)) { new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aFuncAndToken.mToken.marker) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; _tcscpy(result_to_return_dll,aFuncAndToken.mToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; ITOA64(aFuncAndToken.mToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken.mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. new_buf = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } result_to_return_dll = new_buf; ITOA64(aFuncAndToken.mToken.value_int64, result_to_return_dll); } LeaveCriticalSection(&g_CriticalAhkFunction); return result_to_return_dll; } else // UDF { //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); EnterCriticalSection(&g_CriticalAhkFunction); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; if (aParamsCount) { ExprTokenType **new_mem = (ExprTokenType**)realloc(aFuncAndToken.param,sizeof(ExprTokenType)*aParamsCount); if (!new_mem) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param = new_mem; } else aFuncAndToken.param = NULL; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; LPTSTR new_buf; for (int i = 0;(aFunc->mParamCount > i || aFunc->mIsVariadic) && aParamsCount>i;i++) { aFuncAndToken.param[i] = &aFuncAndToken.params[i]; aFuncAndToken.param[i]->symbol = SYM_STRING; new_buf = (LPTSTR)realloc(aFuncAndToken.param[i]->marker,(_tcslen(*params[i])+1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func); LeaveCriticalSection(&g_CriticalAhkFunction); return _T(""); } aFuncAndToken.param[i]->marker = new_buf; _tcscpy(aFuncAndToken.param[i]->marker,*params[i]); // Assign parameters } aFuncAndToken.mFunc = aFunc ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); LeaveCriticalSection(&g_CriticalAhkFunction); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. //VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. //int var_backup_count; // The number of items in the above array. //if (func.mInstances > 0) // Backup is needed. //if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. // return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); //for (int aParamCount = 0;func.mParamCount > aParamCount && aFuncAndToken->mParamCount > aParamCount;aParamCount++) // func.mParam[aParamCount].var->AssignString(aFuncAndToken->param[aParamCount]); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) ResultType aResult; FuncCallData func_call; // ExprTokenType &aResultToken = aResultToken_to_return ; bool result = func.Call(func_call,aResult,aResultToken,aFuncAndToken->param,(int) aFuncAndToken->mParamCount,false); // Call the UDF. DEBUGGER_STACK_POP() LPTSTR new_buf; if (result) { switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.var->Contents()) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.marker) + 1)*sizeof(TCHAR)); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } aFuncAndToken->result_to_return_dll = new_buf; ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: new_buf = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); if (!new_buf) { g_script.ScriptError(ERR_OUTOFMEM,func.mName); return; } result_to_return_dll = new_buf; sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { VARIANT *variants[10] = {&param1,&param2,&param3,&param4,&param5,&param6,&param7,&param8,&param9,&param10}; int aParamsCount = 0; for (;aParamsCount < 10;aParamsCount++) if (variants[aParamsCount]->vt == VT_ERROR) break; if (aParamsCount < aFunc->mMinParams) { g_script.ScriptError(ERR_TOO_FEW_PARAMS); VARIANT &r = aFuncAndTokenToReturn[returnCount + 1].variant_to_return_dll; r.vt = VT_NULL ; return r ; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; EnterCriticalSection(&g_CriticalAhkFunction); ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); if (!aParam) { g_script.ScriptError(ERR_OUTOFMEM,func); VARIANT ret = {}; ret.vt = NULL; LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } for (int i = 0;aFunc->mParamCount > i && aParamsCount>i;i++) { aParam[i] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); if (!aParam[i]) { VARIANT ret = {}; ret.vt = NULL; LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } aParam[i]->symbol = SYM_VAR; aParam[i]->var = (Var*)alloca(sizeof(Var)); if (!aParam[i]->var) { VARIANT ret = {}; ret.vt = NULL; LeaveCriticalSection(&g_CriticalAhkFunction); return ret; } // prepare variable aParam[i]->var->mType = VAR_NORMAL; aParam[i]->var->mAttrib = 0; aParam[i]->var->mByteCapacity = 0; aParam[i]->var->mHowAllocated = ALLOC_MALLOC; AssignVariant(*aParam[i]->var, *variants[i],false); } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamsCount); // free all variables in case memory was allocated for (int i = 0;i < aParamsCount;i++) aParam[i]->var->Free(); TokenToVariant(aResultToken, variant_to_return_dll); LeaveCriticalSection(&g_CriticalAhkFunction); return variant_to_return_dll; } else // UDF { EnterCriticalSection(&g_CriticalAhkFunction); for (int i = 0;aFunc->mParamCount > i;i++) AssignVariant(*aFunc->mParam[i].var, *variants[i],false); if (++returnCount > 9) returnCount = 0 ; FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; aFuncAndToken.mParamCount = aFunc->mParamCount < aParamsCount ? aFunc->mParamCount : aParamsCount; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); LeaveCriticalSection(&g_CriticalAhkFunction); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; LeaveCriticalSection(&g_CriticalAhkFunction); return r ; } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. //VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. //int var_backup_count; // The number of items in the above array. //if (func.mInstances > 0) // Backup is needed. //if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. //return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/globaldata.cpp b/source/globaldata.cpp index acb1fd8..47013a7 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,545 +1,546 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() // for compiled AutoHotkey.exe #ifdef _USRDLL bool g_Reloading = false; +bool g_Loading = false; #endif HINSTANCE g_hInstance = NULL; // Set by WinMain(). HMODULE g_hMemoryModule = NULL; // Set by DllMain() used for COM DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; CRITICAL_SECTION g_CriticalHeapBlocks; CRITICAL_SECTION g_CriticalAhkFunction; UINT g_DefaultScriptCodepage = CP_ACP; bool g_ReturnNotExit; // for ahkExec/addScript/addFile bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL PVOID g_ExceptionHandler = NULL; SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. static int GetScreenDPI() { // The DPI setting can be different for each screen axis, but // apparently it is such a rare situation that it is not worth // supporting it. So we just retrieve the X axis DPI. HDC hdc = GetDC(NULL); int dpi = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); return dpi; } int g_ScreenDPI = GetScreenDPI(); MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; TCHAR g_default_pwd0; TCHAR g_default_pwd1; TCHAR g_default_pwd2; TCHAR g_default_pwd3; TCHAR g_default_pwd4; TCHAR g_default_pwd5; TCHAR g_default_pwd6; TCHAR g_default_pwd7; TCHAR g_default_pwd8; TCHAR g_default_pwd9; TCHAR *g_default_pwd[] = {&g_default_pwd0,&g_default_pwd1,&g_default_pwd2,&g_default_pwd3,&g_default_pwd4,&g_default_pwd5,&g_default_pwd6,&g_default_pwd7,&g_default_pwd8,&g_default_pwd9,0,0}; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("BreakIf"), 1, 2, 2, {1, 0}} , {_T("Continue"), 0, 1, 1, NULL}, {_T("ContinueIf"), 1, 2, 2, {1, 0}} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("Finally"), 0, 0, 0, NULL} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) diff --git a/source/globaldata.h b/source/globaldata.h index adedd4b..6a86878 100644 --- a/source/globaldata.h +++ b/source/globaldata.h @@ -1,371 +1,372 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" #ifdef _USRDLL extern bool g_Reloading; +extern bool g_Loading; #endif extern HRSRC g_hResource; // for compiled AutoHotkey.exe extern HINSTANCE g_hInstance; extern HMODULE g_hMemoryModule; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; extern ATOM g_ClassRegistered; extern ATOM g_ClassSplashRegistered; extern CRITICAL_SECTION g_CriticalRegExCache; extern CRITICAL_SECTION g_CriticalHeapBlocks; extern CRITICAL_SECTION g_CriticalAhkFunction; extern UINT g_DefaultScriptCodepage; extern bool g_ReturnNotExit; // for ahkExec/addScript/addFile 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; #ifndef MINIDLL extern HWND g_hWndSplash; // The SplashText window. extern HFONT g_hFontSplash; #endif extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. 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. #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_HookReceiptOfLControlMeansAltGr; extern DWORD g_IgnoreNextLControlDown; extern DWORD g_IgnoreNextLControlUp; extern BYTE g_MenuMaskKey; // L38: See #MenuMaskKey. // 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_Warn_UseUnsetLocal; extern WarnMode g_Warn_UseUnsetGlobal; extern WarnMode g_Warn_UseEnv; extern WarnMode g_Warn_LocalSameAsGlobal; #ifndef MINIDLL extern PVOID g_ExceptionHandler; extern SingleInstanceType g_AllowOnlyOneInstance; #endif extern bool g_persistent; #ifndef MINIDLL extern bool g_NoTrayIcon; #endif #ifdef AUTOHOTKEYSC extern bool g_AllowMainWindow; #endif extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_AutoExecTimerExists; #ifndef MINIDLL extern bool g_InputTimerExists; #endif extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; #ifndef MINIDLL extern bool g_IsSuspended; #endif extern BOOL g_WriteCacheDisabledInt64; extern BOOL g_WriteCacheDisabledDouble; extern BOOL g_NoEnv; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; #ifndef MINIDLL extern int g_MaxHistoryKeys; #endif extern VarSizeType g_MaxVarCapacity; #ifndef MINIDLL extern UCHAR g_MaxThreadsPerHotkey; #endif extern int g_MaxThreadsTotal; #ifndef MINIDLL extern int g_MaxHotkeysPerInterval; extern int g_HotkeyThrottleInterval; #endif extern bool g_MaxThreadsBuffer; extern SendLevelType g_InputLevel; #ifndef MINIDLL extern HotCriterionType g_HotCriterion; extern LPTSTR g_HotWinTitle; extern LPTSTR g_HotWinText; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #if (expression). See globaldata.cpp for comments. extern int g_HotExprIndex; extern Line **g_HotExprLines; extern int g_HotExprLineCount; extern int g_HotExprLineCountMax; extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern int g_ScreenDPI; extern MenuTypeType g_MenuIsVisible; #endif extern int g_nMessageBoxes; #ifndef MINIDLL extern int g_nInputBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern InputBoxType g_InputBox[MAX_INPUTBOXES]; extern SplashType g_Progress[MAX_PROGRESS_WINDOWS]; extern SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS]; extern GuiType **g_gui; extern int g_guiCount, g_guiCountMax; #endif extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorStruct *g_MsgMonitor; // An array to be allocated upon first use (if any). extern int g_MsgMonitorCount; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern Func *g_SortFunc; extern TCHAR g_delimiter; extern TCHAR g_DerefChar; extern TCHAR g_EscapeChar; #ifndef MINIDLL // 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 bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSSendRaw; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; #endif // Global objects: extern Var *g_ErrorLevel; #ifndef MINIDLL extern input_type g_input; #endif EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; #ifndef MINIDLL extern int g_IconTray; extern int g_IconTraySuspend; #endif extern DWORD g_OriginalTimeout; EXTERN_G; extern global_struct g_default, *g_array; extern TCHAR g_WorkingDir[MAX_PATH]; // Explicit size needed here in .h file for use with sizeof(). extern LPTSTR g_WorkingDirOrig; extern bool g_ContinuationLTrim; 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; #ifndef MINIDLL extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; #endif extern DWORD g_TimeLastInputPhysical; #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE extern bool g_KeyHistoryToFile; #endif #endif // MINIDLL extern TCHAR g_default_pwd0; extern TCHAR g_default_pwd1; extern TCHAR g_default_pwd2; extern TCHAR g_default_pwd3; extern TCHAR g_default_pwd4; extern TCHAR g_default_pwd5; extern TCHAR g_default_pwd6; extern TCHAR g_default_pwd7; extern TCHAR g_default_pwd8; extern TCHAR g_default_pwd9; extern TCHAR *g_default_pwd[]; // 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. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ if (!g_AutoExecTimerExists)\ g_AutoExecTimerExists = SetTimer(g_hWnd, TIMER_ID_AUTOEXEC, aTimeoutValue, AutoExecSectionTimeout);\ } // v1.0.39 for above: Removed the call to ExitApp() upon failure. See SET_MAIN_TIMER for details. #ifndef MINIDLL #define SET_INPUT_TIMER(aTimeoutValue) \ if (!g_InputTimerExists)\ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); #endif // 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; // See above comment about g->AllowThreadToBeInterrupted. #define KILL_AUTOEXEC_TIMER \ {\ if (g_AutoExecTimerExists && KillTimer(g_hWnd, TIMER_ID_AUTOEXEC))\ g_AutoExecTimerExists = false;\ } #ifndef MINIDLL #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #endif #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif
tinku99/ahkdll
3e74e2f88817d5c532dafc633d922911ec0c7033
Changed Exception Handler to disable Hook only on access violation
diff --git a/source/AutoHotkey.cpp b/source/AutoHotkey.cpp index 26fe4ea..c499542 100644 --- a/source/AutoHotkey.cpp +++ b/source/AutoHotkey.cpp @@ -1,356 +1,346 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifndef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "LiteUnzip.h" // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: #ifdef _DEBUG g_hResource = FindResource(NULL, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(NULL, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(NULL, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif g_hInstance = hInstance; InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; #ifndef AUTOHOTKEYSC /* HotKeyIt start AutoHotkey.ahk in same folder as usual #ifdef _DEBUG TCHAR *script_filespec = _T("Test\\Test.ahk"); #else */ TCHAR *script_filespec = NULL; // Set default as "unspecified/omitted". //#endif #endif // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name. { param = __targv[i]; // For performance and convenience. if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; #ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe). else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= __argc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(__targv[i], TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #endif #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. #ifdef AUTOHOTKEYSC --i; // Make the loop process this item again so that it will be treated as a script param. #else if (!g_hResource) // Only apply if it is not a compiled AutoHotkey.exe script_filespec = param; // The first unrecognized switch must be the script filespec, by design. else --i; // Make the loop process this item again so that it will be treated as a script param. #endif } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); global_init(*g); // Set defaults. // Set up the basics of the script: #ifdef AUTOHOTKEYSC if (g_script.Init(*g, _T(""), restart_mode,0,false) != OK) #else if (g_script.Init(*g, script_filespec, restart_mode,0,false) != OK) // Set up the basics of the script, using the above. #endif return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) -#ifdef STANDALONE - UINT load_result; - if (script_filespec != NULL) - load_result = g_script.LoadFromFile(script_filespec); - else - { - TCHAR INTERNAL_SCRIPT[] = { - #include "Script.ahk" - }; - load_result = g_script.LoadFromText(INTERNAL_SCRIPT); - } -#else + #ifdef AUTOHOTKEYSC UINT load_result = g_script.LoadFromFile(); #else UINT load_result = g_script.LoadFromFile(script_filespec == NULL); -#endif #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No script was loaded or we're in /iLib mode, so nothing more to do. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(50); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.Break(); } #endif - + + // set exception filter to disable hook before exception occures to avoid system/mouse freeze + g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } #endif \ No newline at end of file diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 1b44b11..6b921d3 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,967 +1,970 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; g_hMemoryModule = (HMODULE)lpvReserved; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { if (hThread) { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); } // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray"))) ) // realistically never happens { g_script.ScriptError(_T("No tray mem")); g_script.ExitApp(EXIT_CRITICAL); } else g_script.mTrayMenu->mIncludeStandardItems = true; #endif // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap. InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. { g_Reloading = false; return CRITICAL_ERROR; } // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. { g_Reloading = false; return CRITICAL_ERROR; } } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } LocalFree(dllargv); // free memory allocated by CommandLineToArgvW // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) { g_Reloading = false; return CRITICAL_ERROR; // Realistically should never happen. } var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. { g_Reloading = false; return CRITICAL_ERROR; } // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). { g_Reloading = false; return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. } if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. { g_Reloading = false; return 0; } // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) { g_Reloading = false; return CRITICAL_ERROR; } // Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent. SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE); // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif +#ifndef MINIDLL + // set exception filter to disable hook before exception occures to avoid system/mouse freeze + // also when dll will crash, it will only exit dll thread and try to destroy it, leaving the exe process running + g_ExceptionHandler = AddVectoredExceptionHandler(NULL,DisableHooksOnException); // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: -#ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); g_Reloading = false; //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } EXPORT BOOL ahkTerminate(int timeout = 0) { DWORD lpExitCode = 0; if (hThread == 0) return 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); DWORD tickstart = GetTickCount(); DWORD timetowait = timeout < 0 ? timeout * -1 : timeout; for (;hThread && g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && (timeout == 0 || timetowait > (GetTickCount()-tickstart));) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, OK, 0,timeout < 0 ? SMTO_NORMAL : SMTO_NOTIMEOUTIFNOTHUNG,SLEEP_INTERVAL * 3,0); Sleep(100); // give it a bit time to exit thread } if (g_script.mIsReadyToExecute || hThread) { g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread = NULL; } g_AllowInterruption = TRUE; return 0; } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); g_script.Destroy(); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (!g_script.mIsReadyToExecute) { hThread = NULL; SetLastError(lpExitCode); } } unsigned runThread() { if (hThread && g_script.mIsReadyToExecute) { // Small check to be done to make sure we do not start a new thread before the old is closed int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ((lpExitCode == 0 || lpExitCode == 259) && g_script.mIsReadyToExecute) Sleep(50); // make sure the script is not about to be terminated, because this might lead to problems if (hThread && g_script.mIsReadyToExecute) ahkTerminate(0); } hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); } ResultType terminateDll(int aExitCode) { g_script.Destroy(); g_AllowInterruption = TRUE; hThread = NULL; _endthreadex( (DWORD)aExitCode ); return (ResultType)aExitCode; } EXPORT int ahkReload(int timeout = 0) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT int ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute ||g_Reloading; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) { if (IsUnicode==NULL) return ERROR_INVALID_PARAMETER; *IsUnicode = com_ahkIsUnicode(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT waitexecute,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(waitexecute)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) { // search for TypeLib in current dll WCHAR buf[MAX_PATH * sizeof(WCHAR)]; // LoadTypeLibEx needs Unicode string if (GetModuleFileNameW(g_hInstance, buf, _countof(buf))) hr = LoadTypeLibEx(buf,REGKIND_NONE,&ptlib); else // MemoryModule, search troug g_ListOfMemoryModules and use temp file to extract and load TypeLib file { HMEMORYMODULE hmodule = (HMEMORYMODULE)(g_hMemoryModule); HMEMORYRSRC res = MemoryFindResource(hmodule,_T("TYPELIB"),MAKEINTRESOURCE(1)); if (!res) return TYPE_E_INVALIDSTATE; DWORD resSize = MemorySizeOfResource(hmodule,res); // Path to temp directory + our temporary file name DWORD tempPathLength = GetTempPathW(MAX_PATH, buf); wcscpy(buf + tempPathLength,L"AutoHotkey.MemoryModule.temp.tlb"); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after LoadTypeLib has been called. HANDLE hFile = CreateFileW(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif return TYPE_E_CANTLOADLIBRARY; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,MemoryLoadResource(hmodule,res),resSize,&byteswritten,NULL); diff --git a/source/globaldata.cpp b/source/globaldata.cpp index 356cf80..acb1fd8 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,605 +1,606 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() // for compiled AutoHotkey.exe #ifdef _USRDLL bool g_Reloading = false; #endif HINSTANCE g_hInstance = NULL; // Set by WinMain(). HMODULE g_hMemoryModule = NULL; // Set by DllMain() used for COM DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; CRITICAL_SECTION g_CriticalHeapBlocks; CRITICAL_SECTION g_CriticalAhkFunction; UINT g_DefaultScriptCodepage = CP_ACP; bool g_ReturnNotExit; // for ahkExec/addScript/addFile bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL +PVOID g_ExceptionHandler = NULL; SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. static int GetScreenDPI() { // The DPI setting can be different for each screen axis, but // apparently it is such a rare situation that it is not worth // supporting it. So we just retrieve the X axis DPI. HDC hdc = GetDC(NULL); int dpi = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); return dpi; } int g_ScreenDPI = GetScreenDPI(); MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; TCHAR g_default_pwd0; TCHAR g_default_pwd1; TCHAR g_default_pwd2; TCHAR g_default_pwd3; TCHAR g_default_pwd4; TCHAR g_default_pwd5; TCHAR g_default_pwd6; TCHAR g_default_pwd7; TCHAR g_default_pwd8; TCHAR g_default_pwd9; TCHAR *g_default_pwd[] = {&g_default_pwd0,&g_default_pwd1,&g_default_pwd2,&g_default_pwd3,&g_default_pwd4,&g_default_pwd5,&g_default_pwd6,&g_default_pwd7,&g_default_pwd8,&g_default_pwd9,0,0}; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("BreakIf"), 1, 2, 2, {1, 0}} , {_T("Continue"), 0, 1, 1, NULL}, {_T("ContinueIf"), 1, 2, 2, {1, 0}} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("Finally"), 0, 0, 0, NULL} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {_T("IniRead"), 2, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) , {_T("IniWrite"), 3, 4, 4, NULL} // Value, Filespec, Section, Key , {_T("IniDelete"), 2, 3, 3, NULL} // Filespec, Section, Key // These require so few parameters due to registry loops, which provide the missing parameter values // automatically. In addition, RegRead can't require more than 1 param since the 2nd param is // an option/obsolete parameter: , {_T("RegRead"), 1, 5, 5 H, NULL} // output var, (ValueType [optional]), RegKey, RegSubkey, ValueName , {_T("RegWrite"), 0, 5, 5, NULL} // ValueType, RegKey, RegSubKey, ValueName, Value (set to blank if omitted?) , {_T("RegDelete"), 0, 3, 3, NULL} // RegKey, RegSubKey, ValueName , {_T("SetRegView"), 1, 1, 1, NULL} , {_T("OutputDebug"), 1, 1, 1, NULL} , {_T("SetKeyDelay"), 0, 3, 3, {1, 2, 0}} // Delay in ms (numeric, negative allowed), PressDuration [, Play] , {_T("SetMouseDelay"), 1, 2, 2, {1, 0}} // Delay in ms (numeric, negative allowed) [, Play] , {_T("SetWinDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetControlDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetBatchLines"), 1, 1, 1, NULL} // Can be non-numeric, such as 15ms, or a number (to indicate line count). , {_T("SetTitleMatchMode"), 1, 1, 1, NULL} // Allowed values: 1, 2, slow, fast , {_T("SetFormat"), 2, 2, 2, NULL} // Float|Integer, FormatString (for float) or H|D (for int) , {_T("FormatTime"), 1, 3, 3 H, NULL} // OutputVar, YYYYMMDDHH24MISS, Format (format is last to avoid having to escape commas in it). , {_T("Suspend"), 0, 1, 1, NULL} // On/Off/Toggle/Permit/Blank (blank is the same as toggle) , {_T("Pause"), 0, 2, 2, NULL} // On/Off/Toggle/Blank (blank is the same as toggle), AlwaysAffectUnderlying , {_T("AutoTrim"), 1, 1, 1, NULL} // On/Off , {_T("StringCaseSense"), 1, 1, 1, NULL} // On/Off/Locale , {_T("DetectHiddenWindows"), 1, 1, 1, NULL} // On/Off , {_T("DetectHiddenText"), 1, 1, 1, NULL} // On/Off , {_T("BlockInput"), 1, 1, 1, NULL} // On/Off , {_T("SetNumlockState"), 0, 1, 1, NULL} // On/Off/AlwaysOn/AlwaysOff or blank (unspecified) to return to normal. , {_T("SetScrollLockState"), 0, 1, 1, NULL} // same , {_T("SetCapslockState"), 0, 1, 1, NULL} // same , {_T("SetStoreCapslockMode"), 1, 1, 1, NULL} // On/Off , {_T("KeyHistory"), 0, 2, 2, NULL}, {_T("ListLines"), 0, 1, 1, NULL} , {_T("ListVars"), 0, 0, 0, NULL}, {_T("ListHotkeys"), 0, 0, 0, NULL} , {_T("Edit"), 0, 0, 0, NULL} , {_T("Reload"), 0, 0, 0, NULL} , {_T("Menu"), 2, 6, 6, NULL} // tray, add, name, label, options, future use , {_T("Gui"), 1, 4, 4, NULL} // Cmd/Add, ControlType, Options, Text , {_T("GuiControl"), 0, 3, 3 H, NULL} // Sub-cmd (defaults to "contents"), ControlName/ID, Text , {_T("GuiControlGet"), 1, 4, 4, NULL} // OutputVar, Sub-cmd (defaults to "contents"), ControlName/ID (defaults to control assoc. with OutputVar), Text/FutureUse , {_T("ExitApp"), 0, 1, 1, {1, 0}} // Optional exit-code. v1.0.48.01: Allow an expression like ACT_EXIT does. , {_T("Shutdown"), 1, 1, 1, {1, 0}} // Seems best to make the first param (the flag/code) mandatory. , {_T("FileEncoding"), 0, 1, 1, NULL} }; // Below is the most maintainable way to determine the actual count? diff --git a/source/globaldata.h b/source/globaldata.h index 0ec12a3..adedd4b 100644 --- a/source/globaldata.h +++ b/source/globaldata.h @@ -1,370 +1,371 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" #ifdef _USRDLL extern bool g_Reloading; #endif extern HRSRC g_hResource; // for compiled AutoHotkey.exe extern HINSTANCE g_hInstance; extern HMODULE g_hMemoryModule; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; extern ATOM g_ClassRegistered; extern ATOM g_ClassSplashRegistered; extern CRITICAL_SECTION g_CriticalRegExCache; extern CRITICAL_SECTION g_CriticalHeapBlocks; extern CRITICAL_SECTION g_CriticalAhkFunction; extern UINT g_DefaultScriptCodepage; extern bool g_ReturnNotExit; // for ahkExec/addScript/addFile 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; #ifndef MINIDLL extern HWND g_hWndSplash; // The SplashText window. extern HFONT g_hFontSplash; #endif extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. 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. #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_HookReceiptOfLControlMeansAltGr; extern DWORD g_IgnoreNextLControlDown; extern DWORD g_IgnoreNextLControlUp; extern BYTE g_MenuMaskKey; // L38: See #MenuMaskKey. // 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_Warn_UseUnsetLocal; extern WarnMode g_Warn_UseUnsetGlobal; extern WarnMode g_Warn_UseEnv; extern WarnMode g_Warn_LocalSameAsGlobal; #ifndef MINIDLL +extern PVOID g_ExceptionHandler; extern SingleInstanceType g_AllowOnlyOneInstance; #endif extern bool g_persistent; #ifndef MINIDLL extern bool g_NoTrayIcon; #endif #ifdef AUTOHOTKEYSC extern bool g_AllowMainWindow; #endif extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_AutoExecTimerExists; #ifndef MINIDLL extern bool g_InputTimerExists; #endif extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; #ifndef MINIDLL extern bool g_IsSuspended; #endif extern BOOL g_WriteCacheDisabledInt64; extern BOOL g_WriteCacheDisabledDouble; extern BOOL g_NoEnv; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; #ifndef MINIDLL extern int g_MaxHistoryKeys; #endif extern VarSizeType g_MaxVarCapacity; #ifndef MINIDLL extern UCHAR g_MaxThreadsPerHotkey; #endif extern int g_MaxThreadsTotal; #ifndef MINIDLL extern int g_MaxHotkeysPerInterval; extern int g_HotkeyThrottleInterval; #endif extern bool g_MaxThreadsBuffer; extern SendLevelType g_InputLevel; #ifndef MINIDLL extern HotCriterionType g_HotCriterion; extern LPTSTR g_HotWinTitle; extern LPTSTR g_HotWinText; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #if (expression). See globaldata.cpp for comments. extern int g_HotExprIndex; extern Line **g_HotExprLines; extern int g_HotExprLineCount; extern int g_HotExprLineCountMax; extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern int g_ScreenDPI; extern MenuTypeType g_MenuIsVisible; #endif extern int g_nMessageBoxes; #ifndef MINIDLL extern int g_nInputBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern InputBoxType g_InputBox[MAX_INPUTBOXES]; extern SplashType g_Progress[MAX_PROGRESS_WINDOWS]; extern SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS]; extern GuiType **g_gui; extern int g_guiCount, g_guiCountMax; #endif extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorStruct *g_MsgMonitor; // An array to be allocated upon first use (if any). extern int g_MsgMonitorCount; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern Func *g_SortFunc; extern TCHAR g_delimiter; extern TCHAR g_DerefChar; extern TCHAR g_EscapeChar; #ifndef MINIDLL // 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 bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSSendRaw; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; #endif // Global objects: extern Var *g_ErrorLevel; #ifndef MINIDLL extern input_type g_input; #endif EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; #ifndef MINIDLL extern int g_IconTray; extern int g_IconTraySuspend; #endif extern DWORD g_OriginalTimeout; EXTERN_G; extern global_struct g_default, *g_array; extern TCHAR g_WorkingDir[MAX_PATH]; // Explicit size needed here in .h file for use with sizeof(). extern LPTSTR g_WorkingDirOrig; extern bool g_ContinuationLTrim; 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; #ifndef MINIDLL extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; #endif extern DWORD g_TimeLastInputPhysical; #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE extern bool g_KeyHistoryToFile; #endif #endif // MINIDLL extern TCHAR g_default_pwd0; extern TCHAR g_default_pwd1; extern TCHAR g_default_pwd2; extern TCHAR g_default_pwd3; extern TCHAR g_default_pwd4; extern TCHAR g_default_pwd5; extern TCHAR g_default_pwd6; extern TCHAR g_default_pwd7; extern TCHAR g_default_pwd8; extern TCHAR g_default_pwd9; extern TCHAR *g_default_pwd[]; // 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. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ if (!g_AutoExecTimerExists)\ g_AutoExecTimerExists = SetTimer(g_hWnd, TIMER_ID_AUTOEXEC, aTimeoutValue, AutoExecSectionTimeout);\ } // v1.0.39 for above: Removed the call to ExitApp() upon failure. See SET_MAIN_TIMER for details. #ifndef MINIDLL #define SET_INPUT_TIMER(aTimeoutValue) \ if (!g_InputTimerExists)\ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); #endif // 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; // See above comment about g->AllowThreadToBeInterrupted. #define KILL_AUTOEXEC_TIMER \ {\ if (g_AutoExecTimerExists && KillTimer(g_hWnd, TIMER_ID_AUTOEXEC))\ g_AutoExecTimerExists = false;\ } #ifndef MINIDLL #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #endif #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif diff --git a/source/script.cpp b/source/script.cpp index ff00a84..b0194d5 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,767 +1,768 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL + RemoveVectoredExceptionHandler(g_ExceptionHandler); // Exception handler to remove hooks to avoid system/mouse freeze #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; for (v = 0; v < mVarCount; v++) { if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) mVar[v]->mObject->Release(); mVar[v]->ConvertToNonAliasIfNecessary(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; v++) { if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) mLazyVar[v]->mObject->Release(); mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; v++) { if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } for (v = 0; v < f.mVarCount; v++) { if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; v++) { if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } } // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); #endif } #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); diff --git a/source/util.cpp b/source/util.cpp index fc2d934..034e916 100644 --- a/source/util.cpp +++ b/source/util.cpp @@ -2319,523 +2319,533 @@ HICON ExtractIconFromExecutable(LPTSTR aFilespec, int aIconNumber, int aWidth, i } // Decrements the executable module's reference count or frees the data file mapping. FreeLibrary(hdatafile); } // L20: Fall back to ExtractIcon if the above method failed. This may work on some versions of Windows where // ExtractIcon supports 16-bit "executables" (such as ICL files) that cannot be loaded by LoadLibraryEx. // However, resource ID -1 is not supported, and if multiple icon sizes exist in the file, the first is used // rather than the most appropriate. if (!hicon) hicon = ExtractIcon(0, aFilespec, aIconNumber > 0 ? aIconNumber - 1 : aIconNumber < -1 ? aIconNumber : 0); return hicon; } HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon) // Converts HICON to an HBITMAP that has ahIcon's actual dimensions. // The incoming ahIcon will be destroyed if the caller passes true for aDestroyIcon. // Returns NULL on failure, in which case aDestroyIcon will still have taken effect. // If the icon contains any transparent pixels, they will be mapped to CLR_NONE within // the bitmap so that the caller can detect them. { if (!ahIcon) return NULL; HBITMAP hbitmap = NULL; // Set default. This will be the value returned. HDC hdc_desktop = GetDC(HWND_DESKTOP); HDC hdc = CreateCompatibleDC(hdc_desktop); // Don't pass NULL since I think that would result in a monochrome bitmap. if (hdc) { ICONINFO ii; if (GetIconInfo(ahIcon, &ii)) { BITMAP icon_bitmap; // Find out how big the icon is and create a bitmap compatible with the desktop DC (not the memory DC, // since its bits per pixel (color depth) is probably 1. if (GetObject(ii.hbmColor, sizeof(BITMAP), &icon_bitmap) && (hbitmap = CreateCompatibleBitmap(hdc_desktop, icon_bitmap.bmWidth, icon_bitmap.bmHeight))) // Assign { // To retain maximum quality in case caller needs to resize the bitmap we return, convert the // icon to a bitmap that matches the icon's actual size: HGDIOBJ old_object = SelectObject(hdc, hbitmap); if (old_object) // Above succeeded. { // Use DrawIconEx() vs. DrawIcon() because someone said DrawIcon() always draws 32x32 // regardless of the icon's actual size. // If it's ever needed, this can be extended so that the caller can pass in a background // color to use in place of any transparent pixels within the icon (apparently, DrawIconEx() // skips over transparent pixels in the icon when drawing to the DC and its bitmap): RECT rect = {0, 0, icon_bitmap.bmWidth, icon_bitmap.bmHeight}; // Left, top, right, bottom. HBRUSH hbrush = CreateSolidBrush(CLR_DEFAULT); FillRect(hdc, &rect, hbrush); DeleteObject(hbrush); // Probably something tried and abandoned: FillRect(hdc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH)); DrawIconEx(hdc, 0, 0, ahIcon, icon_bitmap.bmWidth, icon_bitmap.bmHeight, 0, NULL, DI_NORMAL); // Debug: Find out properties of new bitmap. //BITMAP b; //GetObject(hbitmap, sizeof(BITMAP), &b); SelectObject(hdc, old_object); // Might be needed (prior to deleting hdc) to prevent memory leak. } } // It's our responsibility to delete these two when they're no longer needed: DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DeleteDC(hdc); } ReleaseDC(HWND_DESKTOP, hdc_desktop); if (aDestroyIcon) DestroyIcon(ahIcon); return hbitmap; } // Lexikos: Used for menu icons on Windows Vista and later. Some similarities to IconToBitmap, maybe should be merged if IconToBitmap does not specifically need to create a device-dependent bitmap? HBITMAP IconToBitmap32(HICON ahIcon, bool aDestroyIcon) { // Get the icon's internal colour and mask bitmaps. // hbmColor is needed to measure the icon. // hbmMask is needed to generate an alpha channel if the icon does not have one. ICONINFO icon_info; if (!GetIconInfo(ahIcon, &icon_info)) return NULL; HBITMAP hbitmap = NULL; // Set default in case of failure. // Get size of icon's internal bitmap. BITMAP icon_bitmap; if (GetObject(icon_info.hbmColor, sizeof(BITMAP), &icon_bitmap)) { int width = icon_bitmap.bmWidth; int height = icon_bitmap.bmHeight; HDC hdc = CreateCompatibleDC(NULL); if (hdc) { BITMAPINFO bitmap_info = {0}; // Set parameters for 32-bit bitmap. May also be used to retrieve bitmap data from the icon's mask bitmap. BITMAPINFOHEADER &bitmap_header = bitmap_info.bmiHeader; bitmap_header.biSize = sizeof(BITMAPINFOHEADER); bitmap_header.biWidth = width; bitmap_header.biHeight = height; bitmap_header.biBitCount = 32; bitmap_header.biPlanes = 1; // Create device-independent bitmap. UINT *bits; if (hbitmap = CreateDIBSection(hdc, &bitmap_info, 0, (void**)&bits, NULL, 0)) { HGDIOBJ old_object = SelectObject(hdc, hbitmap); if (old_object) // Above succeeded. { // Draw icon onto bitmap. Use DrawIconEx because DrawIcon always draws a large (usually 32x32) icon! DrawIconEx(hdc, 0, 0, ahIcon, 0, 0, 0, NULL, DI_NORMAL); // May be necessary for bits to be in sync, according to documentation for CreateDIBSection: GdiFlush(); // Calculate end of bitmap data. UINT *bits_end = bits + width*height; UINT *this_pixel; // Used in a few loops below. // Check for alpha data. bool has_nonzero_alpha = false; for (this_pixel = bits; this_pixel < bits_end; ++this_pixel) { if (*this_pixel >> 24) { has_nonzero_alpha = true; break; } } if (!has_nonzero_alpha) { // Get bitmap data from the icon's mask. UINT *mask_bits = (UINT*)_alloca(height*width*4); if (GetDIBits(hdc, icon_info.hbmMask, 0, height, (LPVOID)mask_bits, &bitmap_info, 0)) { UINT *this_mask_pixel; // Use the icon's mask to generate alpha data. for (this_pixel = bits, this_mask_pixel = mask_bits; this_pixel < bits_end; ++this_pixel, ++this_mask_pixel) { if (*this_mask_pixel) *this_pixel = 0; else *this_pixel |= 0xff000000; } } else { // GetDIBits failed, simply make the bitmap opaque. for (this_pixel = bits; this_pixel < bits_end; ++this_pixel) *this_pixel |= 0xff000000; } } SelectObject(hdc, old_object); } else { // Probably very rare, but be on the safe side. DeleteObject(hbitmap); hbitmap = NULL; } } DWORD dwError = GetLastError(); DeleteDC(hdc); } } // It's our responsibility to delete these two when they're no longer needed: DeleteObject(icon_info.hbmColor); DeleteObject(icon_info.hbmMask); if (aDestroyIcon) DestroyIcon(ahIcon); return hbitmap; } HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList) { // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP. // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally // in case older OSes can ever have it. HRESULT hresult = !S_OK; // Set default as "failure". HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme")); if (hinstTheme) { typedef HRESULT (WINAPI *MySetWindowThemeType)(HWND, LPCWSTR, LPCWSTR); MySetWindowThemeType DynSetWindowTheme = (MySetWindowThemeType)GetProcAddress(hinstTheme, "SetWindowTheme"); if (DynSetWindowTheme) hresult = DynSetWindowTheme(hwnd, pszSubAppName, pszSubIdList); FreeLibrary(hinstTheme); } return hresult; } //HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags) //{ // // The library must be loaded dynamically, otherwise the app will not launch on OSes older than XP. // // Theme DLL is normally available only on XP+, but an attempt to load it is made unconditionally // // in case older OSes can ever have it. // HRESULT hresult = !S_OK; // Set default as "failure". // HINSTANCE hinstTheme = LoadLibrary(_T("uxtheme")); // if (hinstTheme) // { // typedef HRESULT (WINAPI *MyEnableThemeDialogTextureType)(HWND, DWORD); // MyEnableThemeDialogTextureType DynEnableThemeDialogTexture = (MyEnableThemeDialogTextureType)GetProcAddress(hinstTheme, "EnableThemeDialogTexture"); // if (DynEnableThemeDialogTexture) // hresult = DynEnableThemeDialogTexture(hwnd, dwFlags); // FreeLibrary(hinstTheme); // } // return hresult; //} LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace) // Replaces any escape sequences in aBuf with their reduced equivalent. For example, if aEscapeChar // is accent, Each `n would become a literal linefeed. aBuf's length should always be the same or // lower than when the process started, so there is no chance of overflow. { LPTSTR cp, cp1; for (cp = aBuf; ; ++cp) // Increment to skip over the symbol just found by the inner for(). { for (; *cp && *cp != aEscapeChar; ++cp); // Find the next escape char. if (!*cp) // end of string. break; cp1 = cp + 1; switch (*cp1) { // Only lowercase is recognized for these: case 'a': *cp1 = '\a'; break; // alert (bell) character case 'b': *cp1 = '\b'; break; // backspace case 'f': *cp1 = '\f'; break; // formfeed case 'n': *cp1 = '\n'; break; // newline case 'r': *cp1 = '\r'; break; // carriage return case 't': *cp1 = '\t'; break; // horizontal tab case 'v': *cp1 = '\v'; break; // vertical tab case 's': // space (not always allowed for backward compatibility reasons). if (aAllowEscapedSpace) *cp1 = ' '; //else do nothing extra, just let the standard action for unrecognized escape sequences. break; // Otherwise, if it's not one of the above, the escape-char is considered to // mark the next character as literal, regardless of what it is. Examples: // `` -> ` // `:: -> :: (effectively) // `; -> ; // `c -> c (i.e. unknown escape sequences resolve to the char after the `) } // Below has a final +1 to include the terminator: tmemmove(cp, cp1, _tcslen(cp1) + 1); } return aBuf; } int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter, int aStartIndex, LPCTSTR aLiteralMap) // Returns the index of the next delimiter, taking into account quotes, parentheses, etc. // If the delimiter is not found, returns the length of aBuf. { bool in_quotes = false; int open_parens = 0; for (int mark = aStartIndex; ; ++mark) { if (aBuf[mark] == aDelimiter) { if (!in_quotes && open_parens <= 0 && !(aLiteralMap && aLiteralMap[mark])) // A delimiting comma other than one in a sub-statement or function. return mark; // Otherwise, its a quoted/literal comma or one in parentheses (such as function-call). continue; } switch (aBuf[mark]) { case '"': // There are sections similar this one later below; so see them for comments. in_quotes = !in_quotes; break; case '(': // For our purpose, "(", "[" and "{" can be treated the same. case '[': // If they aren't balanced properly, a later stage will detect it. case '{': // if (!in_quotes) // Literal parentheses inside a quoted string should not be counted for this purpose. ++open_parens; break; case ')': case ']': case '}': if (!in_quotes) --open_parens; // If this makes it negative, validation later on will catch the syntax error. break; case '\0': // Reached the end of the string without finding a delimiter. Return the // index of the null-terminator since that's typically what the caller wants. return mark; //default: some other character; just have the loop skip over it. } } } bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch) // Checks if aStr exists in aList (which is a comma-separated list). // If aStr is blank, aList must start with a delimiting comma for there to be a match. { // Must use a temp. buffer because otherwise there's no easy way to properly match upon strings // such as the following: // if var in string,,with,,literal,,commas TCHAR buf[LINE_SIZE]; TCHAR *next_field, *cp, *end_buf = buf + _countof(buf) - 1; // v1.0.48.01: Performance improved by Lexikos. for (TCHAR *this_field = aList; *this_field; this_field = next_field) // For each field in aList. { for (cp = buf, next_field = this_field; *next_field && cp < end_buf; ++cp, ++next_field) // For each char in the field, copy it over to temporary buffer. { if (*next_field == ',') // This is either a delimiter (,) or a literal comma (,,). { ++next_field; if (*next_field != ',') // It's "," instead of ",," so treat it as the end of this field. break; // Otherwise it's ",," and next_field now points at the second comma; so copy that comma // over as a literal comma then continue copying. } *cp = *next_field; } // The end of this field has been reached (or reached the capacity of the buffer), so terminate the string // in the buffer. *cp = '\0'; if (*buf) // It is possible for this to be blank only for the first field. Example: if var in ,abc { if (aFindExactMatch) { if (!g_tcscmp(aStr, buf)) // Match found return true; } else // Substring match if (g_tcsstr(aStr, buf)) // Match found return true; } else // First item in the list is the empty string. if (aFindExactMatch) // In this case, this is a match if aStr is also blank. { if (!*aStr) return true; } else // Empty string is always found as a substring in any other string. return true; } // for() return false; // No match found. } LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen) { // For each character in aStr: for ( ; *aStr; ++aStr) // For each needle: for (int i = 0; i < aNeedleCount; ++i) // For each character in this needle: for (LPTSTR needle_pos = aNeedle[i], str_pos = aStr; ; ++needle_pos, ++str_pos) { if (!*needle_pos) { // All characters in needle matched aStr at this position, so we've // found our string. If this needle is empty, it implicitly matches // at the first position in the string. aFoundLen = needle_pos - aNeedle[i]; return aStr; } // Otherwise, we haven't reached the end of the needle. If we've reached // the end of aStr, *str_pos and *needle_pos won't match, so the check // below will break out of the loop. if (*needle_pos != *str_pos) // Not a match: continue on to the next needle, or the next starting // position in aStr if this is the last needle. break; } // If the above loops completed without returning, no matches were found. return NULL; } short IsDefaultType(LPTSTR aTypeDef){ static LPTSTR sTypeDef[8] = {_T(" CHAR UCHAR BOOLEAN BYTE ") #ifndef _WIN64 ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR HALF_PTR UHALF_PTR ") #else ,_T(" ATOM LANGID WCHAR WORD SHORT USHORT BYTE TCHAR ") #endif ,_T("") #ifdef _WIN64 ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 HALF_PTR UHALF_PTR ") #else ,_T(" INT UINT FLOAT INT32 LONG LONG32 HFILE HRESULT BOOL COLORREF DWORD DWORD32 LCID LCTYPE LGRPID LRESULT UINT32 ULONG ULONG32 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #endif ,_T(""),_T(""),_T("") #ifdef _WIN64 ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 PTR UPTR INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR PDWORD PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR DWORD_PTR HACCEL HANDLE HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP HENHMETAFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD LPWSTR PHANDLE PHKEY PINT PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 POINTER_UNSIGNED PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T UINT_PTR ULONG_PTR VOID ") #else ,_T(" INT64 UINT64 DOUBLE __int64 LONGLONG LONG64 USN DWORDLONG DWORD64 ULONGLONG ULONG64 ") #endif }; for (int i=0;i<8;i++) { if (tcscasestr(sTypeDef[i],aTypeDef)) return i + 1; } // type was not found return NULL; } DWORD DecompressBuffer(void *aBuffer,LPVOID &aDataBuf, TCHAR *pwd[]) // LiteZip Raw compression { unsigned int hdrsz = 20; TCHAR pw[1024] = {0}; if (pwd && pwd[0]) for(unsigned int i = 0;pwd[i];i++) pw[i] = (TCHAR)*pwd[i]; ULONG aSizeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 8); DWORD aSizeEncrypted = *(DWORD*)((UINT_PTR)aBuffer + 16); DWORD hash; BYTE *aDataEncrypted = NULL; HashData((LPBYTE)aBuffer + hdrsz,aSizeEncrypted?aSizeEncrypted:aSizeCompressed,(LPBYTE)&hash,4); if (0x04034b50 == *(ULONG*)(UINT_PTR)aBuffer && hash == *(ULONG*)((UINT_PTR)aBuffer + 4)) { HUNZIP huz; ZIPENTRY ze; DWORD result; ULONG aSizeDeCompressed = *(ULONG*)((UINT_PTR)aBuffer + 12); aDataBuf = VirtualAlloc(NULL, aSizeDeCompressed, MEM_COMMIT, PAGE_READWRITE); if (aDataBuf) { if (aSizeEncrypted) { typedef BOOL (_stdcall *MyDecrypt)(HCRYPTKEY,HCRYPTHASH,BOOL,DWORD,BYTE*,DWORD*); HMODULE advapi32 = LoadLibrary(_T("advapi32.dll")); MyDecrypt Decrypt = (MyDecrypt)GetProcAddress(advapi32,"CryptDecrypt"); LPSTR aDataEncryptedString = (LPSTR)VirtualAlloc(NULL, aSizeEncrypted, MEM_COMMIT, PAGE_READWRITE); DWORD aSizeEncryptedString = aSizeEncrypted; DWORD aSizeEncryptedTemp = aSizeEncrypted; HCRYPTPROV hProv; HCRYPTKEY hKey; HCRYPTHASH hHash; CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT); CryptCreateHash(hProv,CALG_SHA1,NULL,NULL,&hHash); CryptHashData(hHash,(BYTE *) pw,(DWORD)_tcslen(pw) * sizeof(TCHAR),0); CryptDeriveKey(hProv,CALG_AES_256,hHash,256<<16,&hKey); CryptDestroyHash(hHash); memmove(aDataEncryptedString,(LPBYTE)aBuffer + hdrsz,aSizeEncrypted); Decrypt(hKey,NULL,true,0,(BYTE*)aDataEncryptedString,&aSizeEncryptedString); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,NULL,&aSizeEncryptedTemp,NULL,NULL); if (aSizeEncryptedTemp == 0) { // incorrect password VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } aDataEncrypted = (BYTE*)VirtualAlloc(NULL, aSizeEncryptedTemp, MEM_COMMIT, PAGE_READWRITE); CryptStringToBinaryA(aDataEncryptedString,NULL,CRYPT_STRING_BASE64,aDataEncrypted,&aSizeEncryptedTemp,NULL,NULL); VirtualFree(aDataEncryptedString,aSizeEncrypted,MEM_RELEASE); CryptDestroyKey(hKey); CryptReleaseContext(hProv,0); if (openArchive(&huz,(LPBYTE)aDataEncrypted, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return 0; } } else if (openArchive(&huz,(LPBYTE)aBuffer + hdrsz, aSizeCompressed, ZIP_MEMORY|ZIP_RAW, 0)) { // failed to open archive closeArchive((TUNZIP *)huz); VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); return 0; } ze.CompressedSize = aSizeDeCompressed; ze.UncompressedSize = aSizeDeCompressed; if ((result = unzipEntry((TUNZIP *)huz, aDataBuf, &ze, ZIP_MEMORY))) VirtualFree(aDataBuf,aSizeDeCompressed,MEM_RELEASE); else { closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); return aSizeDeCompressed; } closeArchive((TUNZIP *)huz); if (aDataEncrypted) VirtualFree(aDataEncrypted,aSizeDeCompressed,MEM_RELEASE); } } return 0; } +#ifndef MINIDLL +LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs) +{ + // Disable all hooks to avoid system/mouse freeze + if (pExceptionPtrs->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) + AddRemoveHooks(0); + return EXCEPTION_CONTINUE_SEARCH; +} +#endif + #if defined(_MSC_VER) && defined(_DEBUG) void OutputDebugStringFormat(LPCTSTR fmt, ...) { CString sMsg; va_list ap; va_start(ap, fmt); sMsg.FormatV(fmt, ap); OutputDebugString(sMsg); } #endif diff --git a/source/util.h b/source/util.h index 3ef6d09..0dc8d5c 100644 --- a/source/util.h +++ b/source/util.h @@ -272,521 +272,522 @@ inline size_t rtrim(LPTSTR aStr, size_t aLength = -1) // To improve performance, caller may specify a length (e.g. when it is already known). // v1.0.25: Always returns the new length of the string. This greatly improves the performance of // PerformAssign(). // NOTE: THIS VERSION trims only tabs and spaces. It specifically avoids trimming newlines because // some callers want to retain those. { if (!*aStr) return 0; // The below relies upon this check having been done. // It's done this way in case aStr just happens to be address 0x00 (probably not possible // on Intel & Intel-clone hardware) because otherwise --cp would decrement, causing an // underflow since pointers are probably considered unsigned values, which would // probably cause an infinite loop. Extremely unlikely, but might as well try // to be thorough: if (aLength == -1) aLength = _tcslen(aStr); // Set aLength for use below and also as the return value. for (LPTSTR cp = aStr + aLength - 1; ; --cp, --aLength) { if (!IS_SPACE_OR_TAB(*cp)) { cp[1] = '\0'; return aLength; } // Otherwise, it is a space or tab... if (cp == aStr) // ... and we're now at the first character of the string... { if (IS_SPACE_OR_TAB(*cp)) // ... and that first character is also a space or tab... { *cp = '\0'; // ... so the entire string is made empty... return 0; // Fix for v1.0.39: Must return 0 not aLength in this case. } return aLength; // ... and we return in any case. } // else it's a space or tab, and there are still more characters to check. Let the loop // do its decrements. } } inline void rtrim_literal(LPTSTR aStr, TCHAR aLiteralMap[]) // Caller must ensure that aStr is not NULL. // NOTE: THIS VERSION trims only tabs and spaces which aren't marked as literal (so not "`t" or "` "). // It specifically avoids trimming newlines because some callers want to retain those. { if (!*aStr) return; // The below relies upon this check having been done. // It's done this way in case aStr just happens to be address 0x00 (probably not possible // on Intel & Intel-clone hardware) because otherwise --cp would decrement, causing an // underflow since pointers are probably considered unsigned values, which would // probably cause an infinite loop. Extremely unlikely, but might as well try // to be thorough: for (size_t last = _tcslen(aStr) - 1; ; --last) { if (!IS_SPACE_OR_TAB(aStr[last]) || aLiteralMap[last]) // It's not a space or tab, or it's a literal one. { aStr[last + 1] = '\0'; return; } // Otherwise, it is a space or tab... if (last == 0) // ... and we're now at the first character of the string... { if (IS_SPACE_OR_TAB(aStr[last])) // ... and that first character is also a space or tab... *aStr = '\0'; // ... so the entire string is made empty. return; // ... and we return in any case. } // else it's a space or tab, and there are still more characters to check. Let the loop // do its decrements. } } inline size_t rtrim_with_nbsp(LPTSTR aStr, size_t aLength = -1) // Returns the new length of the string. // Caller must ensure that aStr is not NULL. // To improve performance, caller may specify a length (e.g. when it is already known). // Same as rtrim but also gets rid of those annoying nbsp (non breaking space) chars that sometimes // wind up on the clipboard when copied from an HTML document, and thus get pasted into the text // editor as part of the code (such as the sample code in some of the examples). { if (!*aStr) return 0; // The below relies upon this check having been done. if (aLength == -1) aLength = _tcslen(aStr); // Set aLength for use below and also as the return value. for (LPTSTR cp = aStr + aLength - 1; ; --cp, --aLength) { if (!IS_SPACE_OR_TAB_OR_NBSP(*cp)) { cp[1] = '\0'; return aLength; } if (cp == aStr) { if (IS_SPACE_OR_TAB_OR_NBSP(*cp)) // ... and that first character is also a space or tab... { *cp = '\0'; // ... so the entire string is made empty... return 0; // Fix for v1.0.39: Must return 0 not aLength in this case. } return aLength; // ... and we return in any case. } } } inline size_t trim(LPTSTR aStr, size_t aLength = -1) // Caller must ensure that aStr is not NULL. // Returns new length of aStr. // To improve performance, caller may specify a length (e.g. when it is already known). // NOTE: THIS VERSION trims only tabs and spaces. It specifically avoids // trimming newlines because some callers want to retain those. { aLength = ltrim(aStr, aLength); // It may return -1 to indicate that it still doesn't know the length. return rtrim(aStr, aLength); // v1.0.25: rtrim() always returns the new length of the string. This greatly improves the // performance of PerformAssign() and possibly other things. } inline size_t strip_trailing_backslash(LPTSTR aPath) // Removes any backslash (if there is one). // Returns length of the new string to allow some callers to avoid another strlen() call. { size_t length = _tcslen(aPath); if (!length) // Below relies on this check having been done to prevent underflow. return length; LPTSTR cp = aPath + length - 1; if (*cp == _T('\\')) { *cp = '\0'; return length - 1; } // Otherwise there no slash to remove, so return the current length. return length; } #define IS_IDENTIFIER_CHAR(c) (cisalnum(c) || (c) == '_' || ((UINT)(c) > 0x7F)) template<typename T> inline T find_identifier_end(T aBuf) // Locates the next character which is not valid in an identifier (var, func, or obj.key name). { while (IS_IDENTIFIER_CHAR(*aBuf)) ++aBuf; return aBuf; } // Transformation is the same in either direction because the end bytes are swapped // and the middle byte is left as-is: #define bgr_to_rgb(aBGR) rgb_to_bgr(aBGR) inline COLORREF rgb_to_bgr(DWORD aRGB) // Fancier methods seem prone to problems due to byte alignment or compiler issues. { return RGB(GetBValue(aRGB), GetGValue(aRGB), GetRValue(aRGB)); } inline bool IsHex(LPCTSTR aBuf) // 10/17/2006: __forceinline worsens performance, but physically ordering it near ATOI64() [via /ORDER] boosts by 3.5%. // Note: AHK support for hex ints reduces performance by only 10% for decimal ints, even in the tightest // of math loops that have SetBatchLines set to -1. { // For whatever reason, omit_leading_whitespace() benches consistently faster (albeit slightly) than // the same code put inline (confirmed again on 10/17/2006, though the difference is hardly anything): //for (; IS_SPACE_OR_TAB(*aBuf); ++aBuf); aBuf = omit_leading_whitespace(aBuf); // i.e. caller doesn't have to have ltrimmed. if (!*aBuf) return false; if (*aBuf == '-' || *aBuf == '+') ++aBuf; // The "0x" prefix must be followed by at least one hex digit, otherwise it's not considered hex: #define IS_HEX(buf) (*buf == '0' && (*(buf + 1) == 'x' || *(buf + 1) == 'X') && isxdigit(*(buf + 2))) return IS_HEX(aBuf); } // As of v1.0.30, ATOI(), ITOA() and the other related functions below are no longer macros // because there are too many places where something like ATOI(++cp) is done, which would be a // bug if not caught since cp would be incremented more than once if the macro referred to that // arg more than once. In addition, a non-comprehensive, simple benchmark shows that the // macros don't perform any better anyway, probably in part because there are many times when // something like ArgToInt(1) is called, which forces the ARG1 macro to be expanded two or more // times within ATOI (when it was a macro). So for now, the below are declared as inline. // However, it seems that the compiler chooses not to make them truly inline, which as it // turns out is probably the right decision since a simple benchmark shows that even with // __forceinline in effect for all of them (which is confirmed to actually force inline), // the performance isn't any better. inline __int64 ATOI64(LPCTSTR buf) // The following comment only applies if the code is a macro or actually put inline by the compiler, // which is no longer true: // A more complex macro is used for ATOI64(), since it is more often called from places where // performance matters (e.g. ACT_ADD). It adds about 500 bytes to the code size in exchange for // a 8% faster math loops. But it's probably about 8% slower when used with hex integers, but // those are so rare that the speed-up seems worth the extra code size: //#define ATOI64(buf) _strtoi64(buf, NULL, 0) // formerly used _atoi64() { return IsHex(buf) ? _tcstoi64(buf, NULL, 16) : _ttoi64(buf); // _atoi64() has superior performance, so use it when possible. } inline unsigned __int64 ATOU64(LPCTSTR buf) { return _tcstoui64(buf, NULL, IsHex(buf) ? 16 : 10); } inline int ATOI(LPCTSTR buf) { // Below has been updated because values with leading zeros were being interpreted as // octal, which is undesirable. // Formerly: #define ATOI(buf) strtol(buf, NULL, 0) // Use zero as last param to support both hex & dec. return IsHex(buf) ? _tcstol(buf, NULL, 16) : _ttoi(buf); // atoi() has superior performance, so use it when possible. } // v1.0.38.01: Make ATOU a macro that refers to ATOI64() to improve performance (takes advantage of _atoi64() // being considerably faster than strtoul(), at least when the number is non-hex). This relies on the fact // that ATOU() and (UINT)ATOI64() produce the same result due to the way casting works. For example: // ATOU("-1") == (UINT)ATOI64("-1") // ATOU("-0xFFFFFFFF") == (UINT)ATOI64("-0xFFFFFFFF") #define ATOU(buf) (UINT)ATOI64(buf) //inline unsigned long ATOU(char *buf) //{ // // As a reminder, strtoul() also handles negative numbers. For example, ATOU("-1") is // // 4294967295 (0xFFFFFFFF) and ATOU("-2") is 4294967294. // return strtoul(buf, NULL, IsHex(buf) ? 16 : 10); //} inline double ATOF(LPCTSTR buf) // Unlike some Unix versions of strtod(), the VC++ version does not seem to handle hex strings // such as "0xFF" automatically. So this macro must check for hex because some callers rely on that. // Also, it uses _strtoi64() vs. strtol() so that more of a double's capacity can be utilized: { return IsHex(buf) ? (double)_tcstoi64(buf, NULL, 16) : _tstof(buf); } inline LPTSTR ITOA(int value, LPTSTR buf) { if (g->FormatInt == 'D') { return _itot(value, buf, 10); } // g->FormatInt == 'h' or 'H' LPTSTR our_buf_temp = buf; // Negative hex numbers need special handling, otherwise something like zero minus one would create // a huge 0xffffffffffffffff value, which would subsequently not be read back in correctly as // a negative number (but UTOA() doesn't need this since there can't be negatives in that case). if (value < 0) { *our_buf_temp++ = '-'; value = -value; } *our_buf_temp++ = '0'; *our_buf_temp++ = 'x'; _itot(value, our_buf_temp, 16); // Must not return the result of the above because it's our_buf_temp and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(our_buf_temp); return buf; } inline LPTSTR ITOA64(__int64 value, LPTSTR buf) { if (g->FormatInt == 'D') { return _i64tot(value, buf, 10); } // g->FormatInt == 'h' or 'H' LPTSTR our_buf_temp = buf; if (value < 0) { *our_buf_temp++ = '-'; value = -value; } *our_buf_temp++ = '0'; *our_buf_temp++ = 'x'; _i64tot(value, our_buf_temp, 16); // Must not return the result of the above because it's our_buf_temp and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(our_buf_temp); return buf; } inline LPTSTR UTOA(unsigned long value, LPTSTR buf) { if (g->FormatInt == 'D') { return _ultot(value, buf, 10); } // g->FormatInt == 'h' or 'H' *buf = '0'; *(buf + 1) = 'x'; _ultot(value, buf + 2, 16); // Must not return the result of the above because it's buf + 2 and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(buf + 2); return buf; } #ifdef _WIN64 inline LPTSTR UTOA64(unsigned __int64 value, LPTSTR buf) { if (g->FormatInt == 'D') { return _ui64tot(value, buf, 10); } // g->FormatInt == 'h' or 'H' *buf = '0'; *(buf + 1) = 'x'; _ui64tot(value, buf + 2, 16); // Must not return the result of the above because it's buf + 2 and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(buf + 2); return buf; } #endif inline LPTSTR HwndToString(HWND aHwnd, LPTSTR aBuf) { aBuf[0] = '0'; aBuf[1] = 'x'; // Use _ultot for performance on 32-bit systems and _ui64tot on 64-bit systems in case it's // possible for HWNDs to have non-zero upper 32-bits: Exp32or64(_ultot,_ui64tot)((size_t)aHwnd, aBuf + 2, 16); return aBuf; } //inline LPTSTR tcscatmove(LPTSTR aDst, LPCTSTR aSrc) //// Same as strcat() but allows aSrc and aDst to overlap. //// Unlike strcat(), it doesn't return aDst. Instead, it returns the position //// in aDst where aSrc was appended. //{ // if (!aDst || !aSrc || !*aSrc) return aDst; // LPTSTR aDst_end = aDst + _tcslen(aDst); // return (LPTSTR)memmove(aDst_end, aSrc, (_tcslen(aSrc) + 1) * sizeof(TCHAR)); // Add 1 to include aSrc's terminator. //} // v1.0.43.03: The following macros support the new "StringCaseSense Locale" setting. This setting performs // 1 to 10 times slower for most things, but has the benefit of seeing characters like ä and Ä as identical // when insensitive. MSDN implies that lstrcmpi() is the same as: // CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, ...) // Note that when MSDN talks about the "word sort" vs. "string sort", it does not mean that strings like // "co-op" and "co-op" are considered equal. Instead, they are considered closer together than the traditional // string sort would see them, so that they wind up together in a sorted list. // And both of them benchmark the same, so lstrcmpi is now used here and in various other places throughout // the program when the new locale-case-insensitive mode is in effect. #define tcscmp2(str1, str2, string_case_sense) ((string_case_sense) == SCS_INSENSITIVE ? _tcsicmp(str1, str2) \ : ((string_case_sense) == SCS_INSENSITIVE_LOCALE ? lstrcmpi(str1, str2) : _tcscmp(str1, str2))) #define g_tcscmp(str1, str2) tcscmp2(str1, str2, ::g->StringCaseSense) // The most common mode is listed first for performance: #define tcsstr2(haystack, needle, string_case_sense) ((string_case_sense) == SCS_INSENSITIVE ? tcscasestr(haystack, needle) \ : ((string_case_sense) == SCS_INSENSITIVE_LOCALE ? lstrcasestr(haystack, needle) : _tcsstr(haystack, needle))) #define g_tcsstr(haystack, needle) tcsstr2(haystack, needle, ::g->StringCaseSense) // For the following, caller must ensure that len1 and len2 aren't beyond the terminated length of the string // because CompareString() might not stop at the terminator when a length is specified. Also, CompareString() // returns 0 on failure, but failure occurs only when parameter/flag is invalid, which should never happen in // this case. #define lstrcmpni(str1, len1, str2, len2) (CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, str1, (int)(len1), str2, (int)(len2)) - 2) // -2 for maintainability // The following macros simplify and make consistent the calls to MultiByteToWideChar(). // MSDN implies that passing -1 for cbMultiByte is the most typical and secure usage because it ensures // that the output is null-terminated: "the resulting wide character string has a null terminator, and the // length returned by the function includes the terminating null character." // // I couldn't find any info on when MB_PRECOMPOSED is needed (if ever). It's the default anyway, // which implies that passing zero (which is quite common in many examples I've seen) is essentially // the same as passing MB_PRECOMPOSED. However, some modes such as CP_UTF8 should never use MB_PRECOMPOSED // or the function will fail. // // #1: FROM ANSI TO UNICODE (UTF-16). dest_size_in_wchars includes the terminator. // From looking at the source to mbstowcs(), it might be faster when the "C" locale is in effect (which is // the default in the absence of setlocale()) than MultiByteToWideChar() depending on how the latter is // implemented. This is because mbstowcs() simply casts the characters to (wchar_t)(unsigned char) without // any other translation at all. Although that behavior is probably identical to MultiByteToWideChar(CP_ACP...), // it's not completely certain -- so it seems best to stick with MultiByteToWideChar() for consistency // (also, avoiding mbstowcs slightly reduces code size). If there's ever a case where performance is // important, create a simple casting loop (see mbstowcs.c for an example) that converts source to dest, // and test if it performs significantly better than MultiByteToWideChar(CP_ACP...). #define ToWideChar(source, dest, dest_size_in_wchars) MultiByteToWideChar(CP_ACP, 0, source, -1, dest, dest_size_in_wchars) // // #2: FROM UTF-8 TO UNICODE (UTF-16). dest_size_in_wchars includes the terminator. MSDN: "For UTF-8, dwFlags must be set to either 0 or MB_ERR_INVALID_CHARS. Otherwise, the function fails with ERROR_INVALID_FLAGS." #define UTF8ToWideChar(source, dest, dest_size_in_wchars) MultiByteToWideChar(CP_UTF8, 0, source, -1, dest, dest_size_in_wchars) // // #3: FROM UNICODE (UTF-16) TO UTF-8. dest_size_in_bytes includes the terminator. #define WideCharToUTF8(source, dest, dest_size_in_bytes) WideCharToMultiByte(CP_UTF8, 0, source, -1, dest, dest_size_in_bytes, NULL, NULL) #define UTF8StrLen(str, cch) MultiByteToWideChar(CP_UTF8, 0, (str), (cch), NULL, 0) #define WideUTF8StrLen(str, cch) WideCharToMultiByte(CP_UTF8, 0, (str), (cch), NULL, 0, NULL, NULL) #ifdef UNICODE #define PosToUTF8Pos WideUTF8StrLen #define LenToUTF8Len(str,pos,len) WideUTF8StrLen(LPCWSTR(str)+int(pos),len) #define UTF8PosToPos UTF8StrLen #define UTF8LenToLen(str,pos,len) UTF8StrLen(LPCSTR(str)+int(pos),len) inline char* WideToUTF8(LPCWSTR str){ int buf_len = WideCharToUTF8(str, NULL, 0); LPSTR buf = (LPSTR) malloc(buf_len); if (buf) WideCharToUTF8(str, buf, buf_len); return buf; } inline LPTSTR UTF8ToWide(LPCSTR str){ int buf_len = UTF8ToWideChar(str, NULL, 0); LPTSTR buf = (LPTSTR) tmalloc(buf_len); if (buf) UTF8ToWideChar(str, buf, buf_len); return buf; } #endif #ifdef UNICODE #define UorA(u,a) (u) #define RegExToUTF8(a) CStringUTF8FromTChar(a) #define TPosToUTF8Pos PosToUTF8Pos #define TLenToUTF8Len LenToUTF8Len #define UTF8PosToTPos UTF8PosToPos #define UTF8LenToTLen UTF8LenToLen #define ToUnicodeOrAsciiEx(wVirtKey, wScanCode, lpKeyState, pszBuff, wFlags, dwhkl) \ ToUnicodeEx((wVirtKey), (wScanCode), (lpKeyState), (LPWSTR)(pszBuff), 2, (wFlags), (dwhkl)) #else #define UorA(u,a) (a) #define RegExToUTF8(a) (a) #define TPosToUTF8Pos(a,b) (b) #define TLenToUTF8Len(a,b,c) (c) #define UTF8PosToTPos(a,b) (b) #define UTF8LenToTLen(a,b,c) (c) #define ToUnicodeOrAsciiEx(wVirtKey, wScanCode, lpKeyState, pszBuff, wFlags, dwhkl) \ ToAsciiEx((wVirtKey), (wScanCode), (lpKeyState), (LPWORD)(pszBuff), (wFlags), (dwhkl)) #endif // v1.0.44.03: Callers now use the following macro rather than the old approach. However, this change // is meaningful only to people who use more than one keyboard layout. In the case of hotstrings: // It seems that the vast majority of them would want the Hotstring monitoring to adhere to the active // window's current keyboard layout rather than the script's. This change is somewhat less certain to // be desirable unconditionally for the Input command (especially invisible/non-V-option Inputs); but it // seems best to use the same approach to avoid calling ToAsciiEx() more than once in cases where a // script has hotstrings and also uses the Input command. Calling ToAsciiEx() twice in such a case would // be likely to aggravate its side effects with dead keys as described at length in the hook/Input code). #define Get_active_window_keybd_layout \ HWND active_window;\ HKL active_window_keybd_layout = GetKeyboardLayout((active_window = GetForegroundWindow())\ ? GetWindowThreadProcessId(active_window, NULL) : 0); // When no foreground window, the script's own layout seems like the safest default. #define FONT_POINT(hdc, p) (-MulDiv(p, GetDeviceCaps(hdc, LOGPIXELSY), 72)) #define DATE_FORMAT_LENGTH 14 // "YYYYMMDDHHMISS" #define IS_LEAP_YEAR(year) ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) int GetYDay(int aMon, int aDay, bool aIsLeapYear); int GetISOWeekNumber(LPTSTR aBuf, int aYear, int aYDay, int aWDay); ResultType YYYYMMDDToFileTime(LPTSTR aYYYYMMDD, FILETIME &aFileTime); DWORD YYYYMMDDToSystemTime2(LPTSTR aYYYYMMDD, SYSTEMTIME *aSystemTime); ResultType YYYYMMDDToSystemTime(LPTSTR aYYYYMMDD, SYSTEMTIME &aSystemTime, bool aDoValidate); LPTSTR FileTimeToYYYYMMDD(LPTSTR aBuf, FILETIME &aTime, bool aConvertToLocalTime = false); LPTSTR SystemTimeToYYYYMMDD(LPTSTR aBuf, SYSTEMTIME &aTime); __int64 YYYYMMDDSecondsUntil(LPTSTR aYYYYMMDDStart, LPTSTR aYYYYMMDDEnd, bool &aFailed); __int64 FileTimeSecondsUntil(FILETIME *pftStart, FILETIME *pftEnd); SymbolType IsPureNumeric(LPCTSTR aBuf, BOOL aAllowNegative = false // BOOL vs. bool might squeeze a little more performance out of this frequently-called function. , BOOL aAllowAllWhitespace = true, BOOL aAllowFloat = false, BOOL aAllowImpure = false); void strlcpy(LPSTR aDst, LPCSTR aSrc, size_t aDstSize); void wcslcpy(LPWSTR aDst, LPCWSTR aSrc, size_t aDstSize); #ifdef UNICODE #define tcslcpy wcslcpy #else #define tcslcpy strlcpy #endif int sntprintf(LPTSTR aBuf, int aBufSize, LPCTSTR aFormat, ...); int sntprintfcat(LPTSTR aBuf, int aBufSize, LPCTSTR aFormat, ...); // Not currently used by anything, so commented out to possibly reduce code size: //int tcslcmp (LPTSTR aBuf1, LPTSTR aBuf2, UINT aLength1 = UINT_MAX, UINT aLength2 = UINT_MAX); int tcslicmp(LPTSTR aBuf1, LPTSTR aBuf2, size_t aLength1 = -1, size_t aLength2 = -1); LPTSTR tcsrstr(LPTSTR aStr, size_t aStr_length, LPCTSTR aPattern, StringCaseSenseType aStringCaseSense, int aOccurrence = 1); LPTSTR lstrcasestr(LPCTSTR phaystack, LPCTSTR pneedle); LPTSTR tcscasestr (LPCTSTR phaystack, LPCTSTR pneedle); UINT StrReplace(LPTSTR aHaystack, LPTSTR aOld, LPTSTR aNew, StringCaseSenseType aStringCaseSense , UINT aLimit = UINT_MAX, size_t aSizeLimit = -1, LPTSTR *aDest = NULL, size_t *aHaystackLength = NULL); size_t PredictReplacementSize(ptrdiff_t aLengthDelta, int aReplacementCount, int aLimit, size_t aHaystackLength , size_t aCurrentLength, size_t aEndOffsetOfCurrMatch); LPTSTR TranslateLFtoCRLF(LPTSTR aString); bool DoesFilePatternExist(LPTSTR aFilePattern, DWORD *aFileAttr = NULL); #ifdef _DEBUG ResultType FileAppend(LPTSTR aFilespec, LPTSTR aLine, bool aAppendNewline = true); #endif LPTSTR ConvertFilespecToCorrectCase(LPTSTR aFullFileSpec); LPTSTR FileAttribToStr(LPTSTR aBuf, DWORD aAttr); unsigned __int64 GetFileSize64(HANDLE aFileHandle); LPTSTR GetLastErrorText(LPTSTR aBuf, int aBufSize, bool aUpdateLastError = false); void AssignColor(LPTSTR aColorName, COLORREF &aColor, HBRUSH &aBrush); COLORREF ColorNameToBGR(LPTSTR aColorName); HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList); //HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags); LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace); int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter = ',', int aStartIndex = 0, LPCTSTR aLiteralMap = NULL); POINT CenterWindow(int aWidth, int aHeight); bool FontExist(HDC aHdc, LPCTSTR aTypeface); void ScreenToWindow(POINT &aPoint, HWND aHwnd); void CoordToScreen(int &aX, int &aY, int aWhichMode); void CoordToScreen(POINT &aPoint, int aWhichMode); void GetVirtualDesktopRect(RECT &aRect); BOOL IsProcess64Bit(HANDLE aHandle); BOOL IsOS64Bit(); LPVOID AllocInterProcMem(HANDLE &aHandle, DWORD aSize, HWND aHwnd, DWORD aExtraAccess = 0); void FreeInterProcMem(HANDLE aHandle, LPVOID aMem); DWORD GetEnvVarReliable(LPCTSTR aEnvVarName, LPTSTR aBuf); DWORD ReadRegString(HKEY aRootKey, LPTSTR aSubkey, LPTSTR aValueName, LPTSTR aBuf, DWORD aBufSize, DWORD aFlag = 0); HBITMAP LoadPicture(LPTSTR aFilespec, int aWidth, int aHeight, int &aImageType, int aIconNumber , bool aUseGDIPlusIfAvailable); HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon); HBITMAP IconToBitmap32(HICON aIcon, bool aDestroyIcon); // Lexikos: Used for menu icons on Vista+. Creates a 32-bit (ARGB) device-independent bitmap from an icon. int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch); LPTSTR InStrAny(LPTSTR aStr, LPTSTR aNeedle[], int aNeedleCount, size_t &aFoundLen); short IsDefaultType(LPTSTR aTypeDef); DWORD DecompressBuffer(void *buffer,LPVOID &aDataBuf, TCHAR *pwd[] = NULL); +LONG WINAPI DisableHooksOnException(PEXCEPTION_POINTERS pExceptionPtrs); int ResourceIndexToId(HMODULE aModule, LPCTSTR aType, int aIndex); // L17: Find integer ID of resource from index. i.e. IconNumber -> resource ID. HICON ExtractIconFromExecutable(LPTSTR aFilespec, int aIconNumber, int aWidth, int aHeight); // L17: Extract icon of the appropriate size from an executable (or compatible) file. #if defined(_MSC_VER) && defined(_DEBUG) void OutputDebugStringFormat(LPCTSTR fmt, ...); // put debug message to the "Output" panel of Visual Studio. #endif #endif
tinku99/ahkdll
8319da6b7ad634cd664b12c5483cc48a67ef7360
Fix #DllImport bug when no parameters
diff --git a/source/script.cpp b/source/script.cpp index 91cc8f7..9496709 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -4913,1121 +4913,1126 @@ inline ResultType Script::IsDirective(LPTSTR aBuf) { // v1.0.35.11 allow changing of load-time directory to increase flexibility. This feature has // been asked for directly or indirectly several times. // If a script ever wants to use a string like "%A_ScriptDir%" literally in an include's filename, // that would not work. But that seems too rare to worry about. // v1.0.45.01: Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root // drive like C: that lacks a backslash (see SetWorkingDir() for details). SetWorkingDir(parameter); return CONDITION_TRUE; } // Since above didn't return, it's a file (or non-existent file, in which case the below will display // the error). This will also display any other errors that occur: return LoadIncludedFile(parameter, is_include_again, ignore_load_failure) ? CONDITION_TRUE : FAIL; #endif } if (IS_DIRECTIVE_MATCH(_T("#NoEnv"))) { g_NoEnv = TRUE; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#NoTrayIcon"))) { #ifndef MINIDLL g_NoTrayIcon = true; #endif return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Persistent"))) { g_persistent = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#SingleInstance"))) { #ifndef MINIDLL g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; // Set default. if (parameter) { if (!_tcsicmp(parameter, _T("Force"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_REPLACE; else if (!_tcsicmp(parameter, _T("Ignore"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_IGNORE; else if (!_tcsicmp(parameter, _T("Off"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_OFF; } #endif return CONDITION_TRUE; } #ifndef MINIDLL if (IS_DIRECTIVE_MATCH(_T("#InstallKeybdHook"))) { // It seems best not to report this warning because a user may want to use partial functionality // of a script on Win9x: //MsgBox("#InstallKeybdHook is not supported on Windows 95/98/Me. This line will be ignored."); if (!g_os.IsWin9x()) Hotkey::RequireHook(HOOK_KEYBD); return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#InstallMouseHook"))) { // It seems best not to report this warning because a user may want to use partial functionality // of a script on Win9x: //MsgBox("#InstallMouseHook is not supported on Windows 95/98/Me. This line will be ignored."); if (!g_os.IsWin9x()) Hotkey::RequireHook(HOOK_MOUSE); return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#UseHook"))) { g_ForceKeybdHook = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } // L4: Handle #if (expression) directive. if (IS_DIRECTIVE_MATCH(_T("#If"))) { if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off. { g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys. g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it. g_HotWinText = _T(""); // g_HotExprIndex = -1; return CONDITION_TRUE; } Func *currentFunc = g->CurrentFunc; // Ensure variable references are global: g->CurrentFunc = NULL; ConvertEscapeSequences(parameter, g_EscapeChar, false); // Normally done in ParseAndAddLine(). // ACT_EXPRESSION will be changed to ACT_IFEXPR after PreparseBlocks() is called so that EvaluateCondition() // can be used and because ACT_EXPRESSION is designed to discard its result (since it normally would not be // used). This can't be done before PreparseBlocks() is called since this isn't really an IF (it has no body). if (!AddLine(ACT_EXPRESSION, &parameter, UCHAR_MAX + 1)) // UCHAR_MAX signals AddLine to avoid pointing any pending labels or functions at the new line. return FAIL; // Above already displayed the error message. Line *hot_expr_line = mLastLine; // Remove the newly added line from the actual script. if (mFirstLine == mLastLine) mFirstLine = NULL; mLastLine = mLastLine->mPrevLine; if (mLastLine) // Will be NULL if no actual code precedes the #if. mLastLine->mNextLine = NULL; mCurrLine = mLastLine; // Restore to previous value: g->CurrentFunc = currentFunc; // Set the new criterion. g_HotCriterion = HOT_IF_EXPR; // Use the expression text to identify hotkey variants. g_HotWinTitle = hot_expr_line->mArg[0].text; g_HotWinText = _T(""); if (g_HotExprLineCount + 1 > g_HotExprLineCountMax) { // Allocate or reallocate g_HotExprLines. g_HotExprLineCountMax += 100; g_HotExprLines = (Line**)realloc(g_HotExprLines, g_HotExprLineCountMax * sizeof(Line**)); } g_HotExprIndex = g_HotExprLineCount++; g_HotExprLines[g_HotExprIndex] = hot_expr_line; // VicinityToText() assumes lines are linked both ways, so clear mPrevLine in case an error occurs when this line is validated. hot_expr_line->mPrevLine = NULL; // The lines could be linked to simplify function resolution (i.e. allow calling PreparseBlocks() for all lines instead of once for each line) -- However, this would cause confusing/irrelevant vicinity lines to be shown if an error occurs. return CONDITION_TRUE; } // L4: Allow #if timeout to be adjusted. if (IS_DIRECTIVE_MATCH(_T("#IfTimeout"))) { if (parameter) g_HotExprTimeout = ATOU(parameter); return CONDITION_TRUE; } if (!_tcsnicmp(aBuf, _T("#IfWin"), 6)) { bool invert = !_tcsnicmp(aBuf + 6, _T("Not"), 3); if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Active"), 6)) // It matches #IfWin[Not]Active. g_HotCriterion = invert ? HOT_IF_NOT_ACTIVE : HOT_IF_ACTIVE; else if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Exist"), 5)) g_HotCriterion = invert ? HOT_IF_NOT_EXIST : HOT_IF_EXIST; else // It starts with #IfWin but isn't Active or Exist: Don't alter g_HotCriterion. return CONDITION_FALSE; // Indicate unknown directive since there are currently no other possibilities. g_HotExprIndex = -1; // L4: For consistency, don't allow mixing of #if and other #ifWin criterion. if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off. { g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys. g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it. g_HotWinText = _T(""); // return CONDITION_TRUE; } LPTSTR hot_win_title = parameter, hot_win_text; // Set default for title; text is determined later. // Scan for the first non-escaped comma. If there is one, it marks the second parameter: WinText. LPTSTR cp, first_non_escaped_comma; for (first_non_escaped_comma = NULL, cp = hot_win_title; ; ++cp) // Increment to skip over the symbol just found by the inner for(). { for (; *cp && !(*cp == g_EscapeChar || *cp == g_delimiter || *cp == g_DerefChar); ++cp); // Find the next escape char, comma, or %. if (!*cp) // End of string was found. break; #define ERR_ESCAPED_COMMA_PERCENT _T("Literal commas and percent signs must be escaped (e.g. `%)") if (*cp == g_DerefChar) return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf); if (*cp == g_delimiter) // non-escaped delimiter was found. { // Preserve the ability to add future-use parameters such as section of window // over which the mouse is hovering, e.g. #IfWinActive, Untitled - Notepad,, TitleBar if (first_non_escaped_comma) // A second non-escaped comma was found. return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf); // Otherwise: first_non_escaped_comma = cp; continue; // Check if there are any more non-escaped commas. } // Otherwise, an escape character was found, so skip over the next character (if any). if (!*(++cp)) // The string unexpectedly ends in an escape character, so avoid out-of-bounds. break; // Otherwise, the ++cp above has skipped over the escape-char itself, and the loop's ++cp will now // skip over the char-to-be-escaped, which is not the one we want (even if it is a comma). } if (first_non_escaped_comma) // Above found a non-escaped comma, so there is a second parameter (WinText). { // Omit whitespace to (seems best to conform to convention/expectations rather than give // strange whitespace flexibility that would likely cause unwanted bugs due to inadvertently // have two spaces instead of one). The user may use `s and `t to put literal leading/trailing // spaces/tabs into these parameters. hot_win_text = omit_leading_whitespace(first_non_escaped_comma + 1); *first_non_escaped_comma = '\0'; // Terminate at the comma to split off hot_win_title on its own. rtrim(hot_win_title, first_non_escaped_comma - hot_win_title); // Omit whitespace (see similar comment above). // The following must be done only after trimming and omitting whitespace above, so that // `s and `t can be used to insert leading/trailing spaces/tabs. ConvertEscapeSequences() // also supports insertion of literal commas via escaped sequences. ConvertEscapeSequences(hot_win_text, g_EscapeChar, true); } else hot_win_text = _T(""); // And leave hot_win_title set to the entire string because there's only one parameter. // The following must be done only after trimming and omitting whitespace above (see similar comment above). ConvertEscapeSequences(hot_win_title, g_EscapeChar, true); // The following also handles the case where both title and text are blank, which could happen // due to something weird but legit like: #IfWinActive, , if (!SetGlobalHotTitleText(hot_win_title, hot_win_text)) return ScriptError(ERR_OUTOFMEM); // So rare that no second param is provided (since its contents may have been temp-terminated or altered above). return CONDITION_TRUE; } // Above completely handles all directives and non-directives that start with "#IfWin". if (IS_DIRECTIVE_MATCH(_T("#Hotstring"))) { if (parameter) { LPTSTR suboption = tcscasestr(parameter, _T("EndChars")); if (suboption) { // Since it's not realistic to have only a couple, spaces and literal tabs // must be included in between other chars, e.g. `n `t has a space in between. // Also, EndChar \t will have a space and a tab since there are two spaces // after the word EndChar. if ( !(parameter = StrChrAny(suboption, _T("\t "))) ) return CONDITION_TRUE; tcslcpy(g_EndChars, ++parameter, _countof(g_EndChars)); ConvertEscapeSequences(g_EndChars, g_EscapeChar, false); return CONDITION_TRUE; } if (!_tcsnicmp(parameter, _T("NoMouse"), 7)) // v1.0.42.03 { g_HSResetUponMouseClick = false; return CONDITION_TRUE; } // Otherwise assume it's a list of options. Note that for compatibility with its // other caller, it will stop at end-of-string or ':', whichever comes first. Hotstring::ParseOptions(parameter, g_HSPriority, g_HSKeyDelay, g_HSSendMode, g_HSCaseSensitive , g_HSConformToCase, g_HSDoBackspace, g_HSOmitEndChar, g_HSSendRaw, g_HSEndCharRequired , g_HSDetectWhenInsideWord, g_HSDoReset); } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#HotkeyModifierTimeout"))) { if (parameter) g_HotkeyModifierTimeout = ATOI(parameter); // parameter was set to the right position by the above macro return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#HotkeyInterval"))) { if (parameter) { g_HotkeyThrottleInterval = ATOI(parameter); // parameter was set to the right position by the above macro if (g_HotkeyThrottleInterval < 10) // values under 10 wouldn't be useful due to timer granularity. g_HotkeyThrottleInterval = 10; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxHotkeysPerInterval"))) { if (parameter) { g_MaxHotkeysPerInterval = ATOI(parameter); // parameter was set to the right position by the above macro if (g_MaxHotkeysPerInterval < 1) // sanity check g_MaxHotkeysPerInterval = 1; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsPerHotkey"))) { if (parameter) { // Use value as a temp holder since it's int vs. UCHAR and can thus detect very large or negative values: value = ATOI(parameter); // parameter was set to the right position by the above macro if (value > MAX_THREADS_LIMIT) // For now, keep this limited to prevent stack overflow due to too many pseudo-threads. value = MAX_THREADS_LIMIT; // UPDATE: To avoid array overflow, this limit must by obeyed except where otherwise documented. else if (value < 1) value = 1; g_MaxThreadsPerHotkey = value; // Note: g_MaxThreadsPerHotkey is UCHAR. } return CONDITION_TRUE; } #endif if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsBuffer"))) { g_MaxThreadsBuffer = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxThreads"))) { if (parameter) { value = ATOI(parameter); // parameter was set to the right position by the above macro if (value > MAX_THREADS_LIMIT) // For now, keep this limited to prevent stack overflow due to too many pseudo-threads. value = MAX_THREADS_LIMIT; // UPDATE: To avoid array overflow, this limit must by obeyed except where otherwise documented. else if (value < 1) value = 1; g_MaxThreadsTotal = value; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#ClipboardTimeout"))) { if (parameter) g_ClipboardTimeout = ATOI(parameter); // parameter was set to the right position by the above macro return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#LTrim"))) { g_ContinuationLTrim = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#WinActivateForce"))) { g_WinActivateForce = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#ErrorStdOut"))) { mErrorStdOut = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxMem"))) { if (parameter) { double valuef = ATOF(parameter); // parameter was set to the right position by the above macro if (valuef > 4095) // Don't exceed capacity of VarSizeType, which is currently a DWORD (4 gig). valuef = 4095; // Don't use 4096 since that might be a special/reserved value for some functions. else if (valuef < 1) valuef = 1; g_MaxVarCapacity = (VarSizeType)(valuef * 1024 * 1024); } return CONDITION_TRUE; } #ifndef MINIDLL if (IS_DIRECTIVE_MATCH(_T("#KeyHistory"))) { if (parameter) { g_MaxHistoryKeys = ATOI(parameter); // parameter was set to the right position by the above macro if (g_MaxHistoryKeys < 0) g_MaxHistoryKeys = 0; else if (g_MaxHistoryKeys > 500) g_MaxHistoryKeys = 500; // Above: There are two reasons for limiting the history file to 500 keystrokes: // 1) GetHookStatus() only has a limited size buffer in which to transcribe the keystrokes. // 500 events is about what you would expect to fit in a 32 KB buffer (it the unlikely event // that the transcribed events create too much text, the text will be truncated, so it's // not dangerous anyway). // 2) To reduce the impression that AutoHotkey designed for key logging (the key history file // is in a very unfriendly format that type of key logging anyway). } return CONDITION_TRUE; } #endif // For the below series, it seems okay to allow the comment flag to contain other reserved chars, // such as DerefChar, since comments are evaluated, and then taken out of the game at an earlier // stage than DerefChar and the other special chars. if (IS_DIRECTIVE_MATCH(_T("#CommentFlag"))) { if (parameter) { if (!*(parameter + 1)) // i.e. the length is 1 { // Don't allow '#' since it's the preprocessor directive symbol being used here. // Seems ok to allow "." to be the comment flag, since other constraints mandate // that at least one space or tab occur to its left for it to be considered a // comment marker. if (*parameter == '#' || *parameter == g_DerefChar || *parameter == g_EscapeChar || *parameter == g_delimiter) return ScriptError(ERR_PARAM1_INVALID, aBuf); // Exclude hotkey definition chars, such as ^ and !, because otherwise // the following example wouldn't work: // User defines ! as the comment flag. // The following hotkey would never be in effect since it's considered to // be commented out: // !^a::run,notepad if (*parameter == '!' || *parameter == '^' || *parameter == '+' || *parameter == '$' || *parameter == '~' || *parameter == '*' || *parameter == '<' || *parameter == '>') // Note that '#' is already covered by the other stmt. above. return ScriptError(ERR_PARAM1_INVALID, aBuf); } tcslcpy(g_CommentFlag, parameter, MAX_COMMENT_FLAG_LENGTH + 1); g_CommentFlagLength = _tcslen(g_CommentFlag); // Keep this in sync with above. } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#EscapeChar"))) { if (parameter) { // Don't allow '.' since that can be part of literal floating point numbers: if ( *parameter == '#' || *parameter == g_DerefChar || *parameter == g_delimiter || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_EscapeChar = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#DerefChar"))) { if (parameter) { if ( *parameter == g_EscapeChar || *parameter == g_delimiter || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) // Fix for v1.0.47.05: Allow deref char to be # as documented. return ScriptError(ERR_PARAM1_INVALID, aBuf); g_DerefChar = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Delimiter"))) { // Attempts to change the delimiter to its starting default (comma) are ignored. // For example, "#Delimiter ," isn't meaningful if the delimiter already is a comma, // which is good because "parameter" has already assumed that the comma is accidental // (not a symbol) and omitted it. if (parameter) { if ( *parameter == '#' || *parameter == g_EscapeChar || *parameter == g_DerefChar || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_delimiter = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MenuMaskKey"))) { // L38: Allow scripts to specify an alternate "masking" key in place of VK_CONTROL. if (parameter && (g_MenuMaskKey = (BYTE)TextToVK(parameter, NULL, true, true))) return CONDITION_TRUE; else return ScriptError(parameter ? ERR_PARAM1_INVALID : ERR_PARAM1_REQUIRED, aBuf); } if (IS_DIRECTIVE_MATCH(_T("#InputLevel"))) { // All hotkeys declared after this directive are assigned the specified InputLevel. // Input generated at a given SendLevel can only trigger hotkeys that belong to the // same or lower InputLevel. Hotkeys at the lowest level (0) cannot be triggered by // any generated input (the same behavior as AHK versions before this feature). // The default level is 0. int group = parameter ? ATOI(parameter) : 0; if (!SendLevelIsValid(group)) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_InputLevel = group; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Warn"))) { if (!parameter) parameter = _T("All"); LPTSTR param1_end = _tcschr(parameter, g_delimiter); size_t param1_length = -1; LPTSTR param2 = _T(""); if (param1_end) { param2 = omit_leading_whitespace(param1_end + 1); param1_end = omit_trailing_whitespace(parameter, param1_end - 1); param1_length = param1_end - parameter + 1; } #define IS_PARAM1_MATCH(value) (!tcslicmp(parameter, value, param1_length)) WarnType warnType; if (IS_PARAM1_MATCH(_T("All")) || !param1_length) warnType = WARN_ALL; else if (IS_PARAM1_MATCH(_T("UseUnsetLocal"))) warnType = WARN_USE_UNSET_LOCAL; else if (IS_PARAM1_MATCH(_T("UseUnsetGlobal"))) warnType = WARN_USE_UNSET_GLOBAL; else if (IS_PARAM1_MATCH(_T("UseEnv"))) warnType = WARN_USE_ENV; else if (IS_PARAM1_MATCH(_T("LocalSameAsGlobal"))) warnType = WARN_LOCAL_SAME_AS_GLOBAL; else return ScriptError(ERR_PARAM1_INVALID, aBuf); WarnMode warnMode; if (!*param2) warnMode = WARNMODE_MSGBOX; // omitted mode parameter implies "MsgBox" mode else if (!_tcsicmp(param2, _T("MsgBox"))) warnMode = WARNMODE_MSGBOX; else if (!_tcsicmp(param2, _T("OutputDebug"))) warnMode = WARNMODE_OUTPUTDEBUG; else if (!_tcsicmp(param2, _T("StdOut"))) warnMode = WARNMODE_STDOUT; else if (!_tcsicmp(param2, _T("Off"))) warnMode = WARNMODE_OFF; else return ScriptError(ERR_PARAM2_INVALID, aBuf); if (warnType == WARN_USE_UNSET_LOCAL || warnType == WARN_ALL) g_Warn_UseUnsetLocal = warnMode; if (warnType == WARN_USE_UNSET_GLOBAL || warnType == WARN_ALL) g_Warn_UseUnsetGlobal = warnMode; if (warnType == WARN_USE_ENV || warnType == WARN_ALL) g_Warn_UseEnv = warnMode; if (warnType == WARN_LOCAL_SAME_AS_GLOBAL || warnType == WARN_ALL) g_Warn_LocalSameAsGlobal = warnMode; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#DllImport"))) { LPTSTR aFuncName = omit_leading_whitespace(parameter); // backup current function // Func currentfunc = **g_script.mFunc; - if (!*(parameter = _tcschr(parameter,','))) + if (!(parameter = _tcschr(parameter,',')) || !*parameter) return ScriptError(ERR_PARAM2_REQUIRED, aBuf); else parameter++; - *(_tcschr(aFuncName,',')) = '\0'; + if (_tcschr(aFuncName,',')) + *(_tcschr(aFuncName,',')) = '\0'; ltrim(parameter); int insert_pos; Func *found_func = FindFunc(aFuncName,_tcslen(aFuncName),&insert_pos); if (found_func) return ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined." else if ( !(found_func = AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos)) ) return FAIL; // It already displayed the error. // restore previous function //memcpy(*g_script.mFunc,&currentfunc,sizeof(Func)); found_func->mBIF = (BuiltInFunctionType)BIF_DllImport; found_func->mIsBuiltIn = true; found_func->mMinParams = 0; TCHAR buf[MAX_PATH]; size_t space_remaining = LINE_SIZE - (parameter-aBuf); if (tcscasestr(parameter, _T("%A_ScriptDir%"))) { BIV_ScriptDir(buf, _T("A_ScriptDir")); StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis. { BIV_SpecialFolderPath(buf, _T("A_AppData")); StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04. { BIV_SpecialFolderPath(buf, _T("A_AppDataCommon")); StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04. { BIV_AhkPath(buf, _T("A_AhkPath")); StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04. { BIV_DllPath(buf, _T("A_DllPath")); StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (_tcschr(parameter,'%')) { return ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_DllPath% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter); } // terminate dll\function name, find it and jump to next parameter - *(_tcschr(parameter,',')) = '\0'; + if (_tcschr(parameter,',')) + *(_tcschr(parameter,',')) = '\0'; HANDLE func_ptr = (HANDLE)ATOI64(parameter); if (!func_ptr) { LPTSTR dll_name = _tcschr(parameter,'\\'); if (dll_name) { *dll_name = '\0'; if (!GetModuleHandle(parameter)) LoadLibrary(parameter); *dll_name = '\\'; } func_ptr = GetDllProcAddress(parameter); } if (!func_ptr ) return ScriptError(ERR_NONEXISTENT_FUNCTION, parameter); parameter = parameter + _tcslen(parameter) + 1; LPTSTR parm = SimpleHeap::Malloc(parameter); // If next parameter starts with digit, it is a shift_param definition and is omitted from paramters list for dllcall int aParamCount = ATOI(parm) ? 0 : 1; - for(;parameter;aParamCount++) - { - if (parameter = _tcschr(parameter,',')) - parameter++; - } - if (aParamCount < 2) + if (*parm) + for(;parameter;aParamCount++) + { + if (parameter = _tcschr(parameter,',')) + parameter++; + } + if (*parm && aParamCount < 2) return ScriptError(ERR_PARAM3_REQUIRED, aBuf); // set max possible parameters for the new function found_func->mParamCount = aParamCount/2; // misuse mGlobalVarCount to hold total amount of parmeters for DllCall found_func->mLazyVarCount = aParamCount; // allocate memory to hold the parameters and defaults ExprTokenType **func_param = (ExprTokenType**)SimpleHeap::Malloc(aParamCount * sizeof(ExprTokenType*)); ExprTokenType **func_defaults = (ExprTokenType**)SimpleHeap::Malloc(found_func->mParamCount * sizeof(ExprTokenType*)); // misuse mParam to hold default parameters found_func->mStaticVar = (Var**)func_param; found_func->mStaticLazyVar = (Var**)func_defaults; // assign function pointer func_param[0] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); func_param[0]->symbol = PURE_INTEGER; func_param[0]->value_int64 = (__int64)func_ptr; + if (!*parm) + return CONDITION_TRUE; ltrim(parm); // set parameters shift if (ATOI(parm)) { int shift_param[MAX_FUNCTION_PARAMS]; int shift_count = 0; for (int i;parm && *parm || *parm != ',';) { if (!(i = ATOI(parm))) break; // next parameter is not number shift_param[shift_count] = i*2; parm = StrChrAny(parm,_T("\t ,")); ltrim(parm); shift_count++; } if (!parm || !_tcschr(parm,',')) return ScriptError(ERR_PARAM3_REQUIRED, aBuf); if (*parm == ',') parm++; // adnvance pointer to next parameter since above left a , // fill left parameters order for (int c = 1; shift_count < found_func->mParamCount;c++) { bool found = false; for (int i = 0; i < shift_count || found;i++) found = shift_param[i] == c*2; if (!found) shift_param[shift_count++] = c*2; } // misuse mLazyVar, allocate memory and fill shift_param found_func->mLazyVar = (Var**)SimpleHeap::Malloc(aParamCount * sizeof(int)); memcpy(found_func->mLazyVar,&shift_param,aParamCount * sizeof(int)); } // fill definition and default parameters for ( aParamCount = 1 ; parm ; aParamCount++ ) { LPTSTR this_parm = parm; if (parm = _tcschr(parm,',')) { *parm = '\0'; parm++; } trim(this_parm); func_param[aParamCount] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); ExprTokenType &this_param = *func_param[aParamCount]; if (this_param.symbol = IsPureNumeric(this_parm,true,true,true,true)) { if (this_param.symbol == PURE_FLOAT) this_param.value_double = ATOF(this_parm); else this_param.value_int64 = ATOI64(this_parm); } else { if (aParamCount % 2) { if (_tcschr(this_parm,'\"') == this_parm && _tcsrchr(this_parm,'\"') == (this_parm + _tcslen(this_parm) - 1)) { this_param.marker = ++this_parm; *(_tcsrchr(this_parm,'\"')) = '\0'; } else this_param.marker = this_parm; } else if (_tcschr(this_parm,'\"') == this_parm && _tcsrchr(this_parm,'\"') == (this_parm + _tcslen(this_parm) - 1)) { this_param.marker = ++this_parm; *(_tcsrchr(this_parm,'\"')) = '\0'; } else { // user variable this_param.var = FindVar(this_parm); if (!this_param.var) // static variable could not be found return ScriptError(_T("The variable name contains illegal character or is not declared."), this_parm); this_param.symbol = SYM_VAR; } } if (!(aParamCount % 2)) { func_defaults[aParamCount/2 - 1] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); memcpy(func_defaults[aParamCount/2 - 1],&this_param,sizeof(ExprTokenType)); } } return CONDITION_TRUE; } // Otherwise, report that this line isn't a directive: return CONDITION_FALSE; } void ScriptTimer::Disable() { mEnabled = false; --g_script.mTimerEnabledCount; #ifndef MINIDLL if (!g_script.mTimerEnabledCount && !g_nLayersNeedingTimer && !Hotkey::sJoyHotkeyCount) #else if (!g_script.mTimerEnabledCount && !g_nLayersNeedingTimer) #endif KILL_MAIN_TIMER // Above: If there are now no enabled timed subroutines, kill the main timer since there's no other // reason for it to exist if we're here. This is because or direct or indirect caller is // currently always ExecUntil(), which doesn't need the timer while its running except to // support timed subroutines. UPDATE: The above is faulty; Must also check g_nLayersNeedingTimer // because our caller can be one that still needs a timer as proven by this script that // hangs otherwise: //SetTimer, Test, on //Sleep, 1000 //msgbox, done //return //Test: //SetTimer, Test, off //return } ResultType Script::UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable , bool aUpdatePriorityOnly) // Caller should specific a blank aPeriod to prevent the timer's period from being changed // (i.e. if caller just wants to turn on or off an existing timer). But if it does this // for a non-existent timer, that timer will be created with the default period as specified in // the constructor. { ScriptTimer *timer; for (timer = mFirstTimer; timer != NULL; timer = timer->mNextTimer) if (timer->mLabel == aLabel) // Match found. break; bool timer_existed = (timer != NULL); if (!timer_existed) // Create it. { if ( !(timer = new ScriptTimer(aLabel)) ) return ScriptError(ERR_OUTOFMEM); if (!mFirstTimer) mFirstTimer = mLastTimer = timer; else { mLastTimer->mNextTimer = timer; // This must be done after the above: mLastTimer = timer; } ++mTimerCount; } // Update its members: if (aEnable && !timer->mEnabled) // Must check both or the mTimerEnabledCount below will be wrong. { // The exception is if the timer already existed but the caller only wanted its priority changed: if (!(timer_existed && aUpdatePriorityOnly)) { timer->mEnabled = true; ++mTimerEnabledCount; SET_MAIN_TIMER // Ensure the API timer is always running when there is at least one enabled timed subroutine. } //else do nothing, leave it disabled. } else if (!aEnable && timer->mEnabled) // Must check both or the below count will be wrong. timer->Disable(); aPeriod = omit_leading_whitespace(aPeriod); // This causes A_Space to be treated as "omitted" rather than zero, so may change the behaviour of some poorly-written scripts, but simplifies the check below which allows -0 to work. if (*aPeriod) // Caller wanted us to update this member. { __int64 period = ATOI64(aPeriod); if (*aPeriod == '-') // v1.0.46.16: Support negative periods to mean "run only once". { timer->mRunOnlyOnce = true; timer->mPeriod = (DWORD)-period; } else // Positive number. v1.0.36.33: Changed from int to DWORD, and ATOI to ATOU, to double its capacity: { timer->mPeriod = (DWORD)period; // Always use this method & check to retain compatibility with existing scripts. timer->mRunOnlyOnce = false; } } if (*aPriority) // Caller wants this member to be changed from its current or default value. timer->mPriority = ATOI(aPriority); // Read any float in a runtime variable reference as an int. if (!(timer_existed && aUpdatePriorityOnly)) // Caller relies on us updating mTimeLastRun in this case. This is done because it's more // flexible, e.g. a user might want to create a timer that is triggered 5 seconds from now. // In such a case, we don't want the timer's first triggering to occur immediately. // Instead, we want it to occur only when the full 5 seconds have elapsed: timer->mTimeLastRun = GetTickCount(); // Below is obsolete, see above for why: // We don't have to kill or set the main timer because the only way this function is called // is directly from the execution of a script line inside ExecUntil(), in which case: // 1) KILL_MAIN_TIMER is never needed because the timer shouldn't exist while in ExecUntil(). // 2) SET_MAIN_TIMER is never needed because it will be set automatically the next time ExecUntil() // calls MsgSleep(). return OK; } Label *Script::FindLabel(LPTSTR aLabelName) // Returns the first label whose name matches aLabelName, or NULL if not found. // v1.0.42: Since duplicates labels are now possible (to support #IfWin variants of a particular // hotkey or hotstring), callers must be aware that only the first match is returned. // This helps performance by requiring on average only half the labels to be searched before // a match is found. { if (!aLabelName || !*aLabelName) return NULL; for (Label *label = mFirstLabel; label != NULL; label = label->mNextLabel) if (!_tcsicmp(label->mName, aLabelName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return label; // Match found. return NULL; // No match found. } ResultType Script::AddLabel(LPTSTR aLabelName, bool aAllowDupe) // Returns OK or FAIL. { if (!*aLabelName) return FAIL; // For now, silent failure because callers should check this beforehand. if (!aAllowDupe && FindLabel(aLabelName)) // Relies on short-circuit boolean order. // Don't attempt to dereference "duplicate_label->mJumpToLine because it might not // exist yet. Example: // label1: // label1: <-- This would be a dupe-error but it doesn't yet have an mJumpToLine. // return return ScriptError(_T("Duplicate label."), aLabelName); LPTSTR new_name = SimpleHeap::Malloc(aLabelName); if (!new_name) return FAIL; // It already displayed the error for us. Label *the_new_label = new Label(new_name); // Pass it the dynamic memory area we created. if (the_new_label == NULL) return ScriptError(ERR_OUTOFMEM); the_new_label->mPrevLabel = mLastLabel; // Whether NULL or not. if (mFirstLabel == NULL) mFirstLabel = the_new_label; else mLastLabel->mNextLabel = the_new_label; // This must be done after the above: mLastLabel = the_new_label; if (!_tcsicmp(new_name, _T("OnClipboardChange"))) mOnClipboardChangeLabel = the_new_label; return OK; } ResultType Script::ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType, ActionTypeType aOldActionType , LPTSTR aActionName, LPTSTR aEndMarker, LPTSTR aLiteralMap, size_t aLiteralMapLength) // Returns OK or FAIL. // aLineText needs to be a string whose contents are modifiable (though the string won't be made any // longer than it is now, so it doesn't have to be of size LINE_SIZE). This helps performance by // allowing the string to be split into sections without having to make temporary copies. { #ifdef _DEBUG if (!aLineText || !*aLineText) return ScriptError(_T("DEBUG: ParseAndAddLine() called incorrectly.")); #endif TCHAR action_name[MAX_VAR_NAME_LENGTH + 1], *end_marker; if (aActionName) // i.e. this function was called recursively with explicit values for the optional params. { _tcscpy(action_name, aActionName); end_marker = aEndMarker; } else if (aActionType == ACT_EXPRESSION) { *action_name = '\0'; end_marker = NULL; // Indicate that there is no action to mark the end of. } else // We weren't called recursively from self, nor is it ACT_EXPRESSION, so set action_name and end_marker the normal way. { for (;;) // A loop with only one iteration so that "break" can be used instead of a lot of nested if's. { int declare_type; LPTSTR cp; if (!_tcsnicmp(aLineText, _T("Global"), 6)) // Checked first because it's more common than the others. { cp = aLineText + 6; // The character after the declaration word. declare_type = g->CurrentFunc ? VAR_DECLARE_GLOBAL : VAR_DECLARE_SUPER_GLOBAL; } else { if (!g->CurrentFunc) // Not inside a function body, so "Local"/"Static" get no special treatment. break; if (!_tcsnicmp(aLineText, _T("Local"), 5)) { cp = aLineText + 5; // The character after the declaration word. declare_type = VAR_DECLARE_LOCAL; } else if (!_tcsnicmp(aLineText, _T("Static"), 6)) // Static also implies local (for functions that default to global). { cp = aLineText + 6; // The character after the declaration word. declare_type = VAR_DECLARE_STATIC; } else // It's not the word "global", "local", or static, so no further checking is done. break; } if (*cp && !IS_SPACE_OR_TAB(*cp)) // There is a character following the word local but it's not a space or tab. break; // It doesn't qualify as being the global or local keyword because it's something like global2. if (*cp && *(cp = omit_leading_whitespace(cp))) // Probably always a true stmt since caller rtrimmed it, but even if not it's handled correctly. { // Check whether the first character is an operator by seeing if it alone would be a // valid variable name. If it's not valid, this doesn't qualify as the global or local // keyword because it's something like this instead: // local := xyz // local += 3 TCHAR orig_char = cp[1]; cp[1] = '\0'; // Temporarily terminate. ResultType result = Var::ValidateName(cp, DISPLAY_NO_ERROR); cp[1] = orig_char; // Undo the termination. if (!result) // It's probably operator, e.g. local = %var% break; } else // It's the word "global", "local", "static" by itself. But only global or static is valid that way (when it's the first line in the function body). { // All of the following must be checked to catch back-to-back conflicting declarations such // as these: // global x // global ; Should be an error because global vars are implied/automatic. // v1.0.48: Lexikos: Added assume-static mode. For now, this requires "static" to be // placed above local or global variable declarations. if (declare_type != VAR_DECLARE_LOCAL // i.e. VAR_DECLARE_GLOBAL or VAR_DECLARE_STATIC (can't due be VAR_DECLARE_NONE due to checks higher above). && mNextLineIsFunctionBody && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_NONE) { g->CurrentFunc->mDefaultVarType = declare_type; // No further action is required for the word "global" or "static" by itself. return OK; } // Otherwise, it's the word "local" by itself (which isn't allowed since it's the default), // or it's the word global or static by itself, but it occurs too far down in the body. return ScriptError(ERR_UNRECOGNIZED_ACTION, aLineText); // Vague error since so rare. } if (mNextLineIsFunctionBody && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_NONE) { // Both of the above must be checked to catch back-to-back conflicting declarations such // as these: // local x // global y ; Should be an error because global vars are implied/automatic. // This line will become first non-directive, non-label line in the function's body. // If the first non-directive, non-label line in the function's body contains // the "local" keyword, everything inside this function will assume that variables // are global unless they are explicitly declared local (this is the opposite of // the default). The converse is also true. if (declare_type != VAR_DECLARE_STATIC) g->CurrentFunc->mDefaultVarType = declare_type == VAR_DECLARE_LOCAL ? VAR_DECLARE_GLOBAL : VAR_DECLARE_LOCAL; // Otherwise, leave it as-is to allow the following: // static x // local y } else // Since this isn't the first line of the function's body, mDefaultVarType has already been set permanently. { if (g->CurrentFunc && declare_type == g->CurrentFunc->mDefaultVarType) // Can't be VAR_DECLARE_NONE at this point. { // Seems best to flag redundant/unnecessary declarations since they might be an indication // to the user that something is being done incorrectly in this function. This errors also // remind the user what mode the function is in: if (declare_type == VAR_DECLARE_GLOBAL) return ScriptError(_T("Global variables must not be declared in this function."), aLineText); if (declare_type == VAR_DECLARE_LOCAL) return ScriptError(_T("Local variables must not be declared in this function."), aLineText); // In assume-static mode, allow declarations in case they contain initializers. // Would otherwise lose the ability to "initialize only once upon startup". //if (declare_type == VAR_DECLARE_STATIC) // return ScriptError("Static variables must not be declared in this function.", aLineText); } } // Since above didn't break or return, a variable is being declared as an exception to the // mode specified by mDefaultVarType. bool open_brace_was_added, belongs_to_if_or_else_or_loop; size_t var_name_length; LPTSTR item; for (belongs_to_if_or_else_or_loop = mLastLine && ACT_IS_IF_OR_ELSE_OR_LOOP(mLastLine->mActionType) , open_brace_was_added = false, item = cp ; *item;) // FOR EACH COMMA-SEPARATED ITEM IN THE DECLARATION LIST. { LPTSTR item_end = StrChrAny(item, _T(", \t=:")); // Comma, space or tab, equal-sign, colon. if (!item_end) // This is probably the last/only variable in the list; e.g. the "x" in "local x" item_end = item + _tcslen(item); var_name_length = (VarSizeType)(item_end - item); Var *var = NULL; int i; if (g->CurrentFunc) { for (i = 0; i < g->CurrentFunc->mParamCount; ++i) // Search by name to find both global and local declarations. if (!tcslicmp(item, g->CurrentFunc->mParam[i].var->mName, var_name_length)) return ScriptError(_T("Parameters must not be declared."), item); // Detect conflicting declarations: var = FindVar(item, var_name_length, NULL, FINDVAR_LOCAL); if (var && (var->Scope() & ~VAR_DECLARED) == (declare_type & ~VAR_DECLARED) && declare_type != VAR_DECLARE_STATIC) var = NULL; // Allow redeclaration using same scope; e.g. "local x := 1 ... local x := 2" down two different code paths. if (!var && declare_type != VAR_DECLARE_GLOBAL) for (i = 0; i < g->CurrentFunc->mGlobalVarCount; ++i) // Explicitly search this array vs calling FindVar() in case func is assume-global. if (!tcslicmp(g->CurrentFunc->mGlobalVar[i]->mName, item, -1, var_name_length)) { var = g->CurrentFunc->mGlobalVar[i]; break; } if (var) return ScriptError(var->IsDeclared() ? ERR_DUPLICATE_DECLARATION : _T("Declaration conflicts with existing var."), item); } if ( !(var = FindOrAddVar(item, var_name_length, declare_type)) ) return FAIL; // It already displayed the error. if (var->Type() != VAR_NORMAL || !tcslicmp(item, _T("ErrorLevel"), var_name_length)) // Shouldn't be declared either way (global or local). return ScriptError(_T("Built-in variables must not be declared."), item); if (declare_type == VAR_DECLARE_GLOBAL) // Can only be true if g->CurrentFunc is non-NULL. { if (g->CurrentFunc->mGlobalVarCount >= MAX_FUNC_VAR_GLOBALS) return ScriptError(_T("Too many declarations."), item); // Short message since it's so unlikely. g->CurrentFunc->mGlobalVar[g->CurrentFunc->mGlobalVarCount++] = var; } else if (declare_type == VAR_DECLARE_SUPER_GLOBAL) { // Ensure the "declared" and "super-global" flags are set, in case this // var was added to the list via a reference prior to the declaration. var->Scope() = declare_type; } item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'. bool convert_the_operator; switch(*item_end) { case ',': // No initializer is present for this variable, so move on to the next one. item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration. continue; // No further processing needed below. case '\0': // No initializer is present for this variable, so move on to the next one. item = item_end; // Set "item" for use by the next iteration. continue; case ':': if (item_end[1] != '=') // Colon with no following '='. return ScriptError(ERR_UNRECOGNIZED_ACTION, item); // Vague error since so rare. item_end += 2; // Point to the character after the ":=". convert_the_operator = false; break; case '=': // Here '=' is clearly an assignment not a comparison, so further below it will be converted to := ++item_end; // Point to the character after the "=". convert_the_operator = true; break; default: // L31: This can be reached by something not officially supported like "global var .= value_to_append". // In previous versions, convert_the_operator was left uninitialized and whether it would work or be // replaced with ".:=" and fail was up to chance. (Testing showed it failed only in Debug mode.) convert_the_operator = false; } LPTSTR right_side_of_operator = item_end; // Save for use by VAR_DECLARE_STATIC below. // Since above didn't "continue", this declared variable also has an initializer. // Add that initializer as a separate line to be executed at runtime. Separate lines // might actually perform better at runtime because most initializers tend to be simple // literals or variables that are simplified into non-expressions at runtime. In addition, // items without an initializer are omitted, further improving runtime performance. // However, the following must be done ONLY after having done the FindOrAddVar() // above, since that may have changed this variable to a non-default type (local or global). // But what about something like "global x, y=x"? Even that should work as long as x // appears in the list prior to initializers that use it. // Now, find the comma (or terminator) that marks the end of this sub-statement. // The search must exclude commas that are inside quoted/literal strings and those that // are inside parentheses (chiefly those of function-calls, but possibly others). item_end += FindNextDelimiter(item_end); // FIND THE NEXT "REAL" COMMA (or the end of the string). // Above has now found the final comma of this sub-statement (or the terminator if there is no comma). LPTSTR terminate_here = omit_trailing_whitespace(item, item_end-1) + 1; // v1.0.47.02: Fix the fact that "x=5 , y=6" would preserve the whitespace at the end of "5". It also fixes wrongly showing a syntax error for things like: static d="xyz" , e = 5 TCHAR orig_char = *terminate_here; *terminate_here = '\0'; // Temporarily terminate (it might already be the terminator, but that's harmless). if (declare_type == VAR_DECLARE_STATIC) { LPTSTR args[] = {var->mName, ConvertEscapeSequences(omit_leading_whitespace(right_side_of_operator), g_EscapeChar, false)}; // UCHAR_MAX signals AddLine to avoid pointing any pending labels or functions at the new line. // Otherwise, ParseAndAddLine could be used like in the section below to optimize simple // assignments, but that would be nearly pointless for static initializers anyway: if (!AddLine(ACT_ASSIGNEXPR, args, UCHAR_MAX + 2)) return FAIL; // Above already displayed the error. mLastLine = mLastLine->mPrevLine; // Restore mLastLine to the last non-'static' line, but leave mCurrLine set to the new line. mLastLine->mNextLine = NULL; // Remove the new line from the main script's linked list of lines. For maintainability: AddLine() unconditionally overwrites mLastLine->mNextLine anyway. if (mLastStaticLine) mLastStaticLine->mNextLine = mCurrLine; else mFirstStaticLine = mCurrLine; mCurrLine->mPrevLine = mLastStaticLine; // Even if NULL. Must be set otherwise VicinityToText() will show the wrong line if this one or one "near" it has an error. mLastStaticLine = mCurrLine; // Some of the checks below could be used to "optimize" static initializers, but since they // will only be executed once each anyway, it doesn't seem useful. Making them expressions // should be overall more consistent and saves worrying about cases like the following, // which previously gave unexpected results: static var := "literal" . "literal" /* // The following is similar to the code used to support default values for function parameters. // So maybe maintain them together. right_side_of_operator = omit_leading_whitespace(right_side_of_operator); if (!_tcsicmp(right_side_of_operator, _T("false"))) var->Assign(_T("0")); else if (!_tcsicmp(right_side_of_operator, _T("true"))) var->Assign(_T("1")); else // The only other supported initializers are "string", integers, and floats. { // Vars could be supported here via FindVar(), but only globals ABOVE this point in // the script would be supported (since other globals don't exist yet; in fact, even // those that do exist don't have any contents yet, so it would be pointless). So it // seems best to wait until full/comprehensive support for expressions is // studied/designed for both statics and parameter-default-values. if (*right_side_of_operator == '"' && terminate_here[-1] == '"') // Quoted/literal string. { ++right_side_of_operator; // Omit the opening-quote from further consideration.
tinku99/ahkdll
2d3118b2f27da6d4186f1fdf0a83ca0d5532846c
Release Objects before vars are deleted, fix #DllImport bugs
diff --git a/source/script.cpp b/source/script.cpp index c6512f7..91cc8f7 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,853 +1,901 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible and delete vars. int v, i; + + for (v = 0; v < mVarCount; v++) + { + if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) + continue; + if (mVar[v]->mType == VAR_ALIAS && mVar[v]->HasObject()) + mVar[v]->mObject->Release(); + mVar[v]->ConvertToNonAliasIfNecessary(); + mVar[v]->Free(); + } + for (v = 0; v < mLazyVarCount; v++) + { + if (mLazyVar[v]->mType == VAR_ALIAS && mLazyVar[v]->HasObject()) + mLazyVar[v]->mObject->Release(); + mLazyVar[v]->ConvertToNonAliasIfNecessary(); + mLazyVar[v]->Free(); + } + free(mLazyVar); + mLazyVar = NULL; // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { + if (f.mStaticVar[v]->mType == VAR_ALIAS && f.mStaticVar[v]->HasObject()) + f.mStaticVar[v]->mObject->Release(); f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); - delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { + if (f.mStaticLazyVar[v]->mType == VAR_ALIAS && f.mStaticLazyVar[v]->HasObject()) + f.mStaticLazyVar[v]->mObject->Release(); f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); - delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { + if (f.mVar[v]->mType == VAR_ALIAS && f.mVar[v]->HasObject()) + f.mVar[v]->mObject->Release(); f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); - delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { + if (f.mLazyVar[v]->mType == VAR_ALIAS && f.mLazyVar[v]->HasObject()) + f.mLazyVar[v]->mObject->Release(); f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); - delete f.mLazyVar[v]; } - if (mFunc[i]->mStaticVar) - free(mFunc[i]->mStaticVar); - if (mFunc[i]->mStaticLazyVarCount) - free(mFunc[i]->mStaticLazyVar); - if (mFunc[i]->mVarCount) - free(mFunc[i]->mVar); - if (mFunc[i]->mLazyVarCount) - free(mFunc[i]->mLazyVar); - delete mFunc[i]; } + // Now all objects are freed and variables can be deleted for (v = 0; v < mVarCount; v++) { // H19 fix not to delete Clipboard wars - if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) + if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD || mVar[v]->mType == VAR_CLIPBOARDALL) continue; - mVar[v]->ConvertToNonAliasIfNecessary(); - mVar[v]->Free(); delete mVar[v]; } free(mVar); mVar = NULL; for (v = 0; v < mLazyVarCount; v++) { - mLazyVar[v]->ConvertToNonAliasIfNecessary(); - mLazyVar[v]->Free(); delete mLazyVar[v]; } free(mLazyVar); mLazyVar = NULL; + // delete static func vars first + for (i = 0; i < mFuncCount; i++) + { + Func &f = *mFunc[i]; + if (f.mIsBuiltIn) + continue; + // Since it doesn't seem feasible to release all var backups created by recursive function + // calls and all tokens in the 'stack' of each currently executing expression, currently + // only static and global variables are released. It seems best for consistency to also + // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). + for (v = 0; v < f.mStaticVarCount; v++) + { + delete f.mStaticVar[v]; + } + for (v = 0; v < f.mStaticLazyVarCount; v++) + { + delete f.mStaticLazyVar[v]; + } + for (v = 0; v < f.mVarCount; v++) + { + delete f.mVar[v]; + } + for (v = 0; v < f.mLazyVarCount; v++) + { + delete f.mLazyVar[v]; + } + if (mFunc[i]->mStaticVar) + free(mFunc[i]->mStaticVar); + if (mFunc[i]->mStaticLazyVarCount) + free(mFunc[i]->mStaticLazyVar); + if (mFunc[i]->mVarCount) + free(mFunc[i]->mVar); + if (mFunc[i]->mLazyVarCount) + free(mFunc[i]->mLazyVar); + delete mFunc[i]; + } + // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); #endif } #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) @@ -4863,1159 +4911,1207 @@ inline ResultType Script::IsDirective(LPTSTR aBuf) DWORD attr = GetFileAttributes(parameter); if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY)) // File exists and its a directory (possibly A_ScriptDir or A_AppData set above). { // v1.0.35.11 allow changing of load-time directory to increase flexibility. This feature has // been asked for directly or indirectly several times. // If a script ever wants to use a string like "%A_ScriptDir%" literally in an include's filename, // that would not work. But that seems too rare to worry about. // v1.0.45.01: Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root // drive like C: that lacks a backslash (see SetWorkingDir() for details). SetWorkingDir(parameter); return CONDITION_TRUE; } // Since above didn't return, it's a file (or non-existent file, in which case the below will display // the error). This will also display any other errors that occur: return LoadIncludedFile(parameter, is_include_again, ignore_load_failure) ? CONDITION_TRUE : FAIL; #endif } if (IS_DIRECTIVE_MATCH(_T("#NoEnv"))) { g_NoEnv = TRUE; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#NoTrayIcon"))) { #ifndef MINIDLL g_NoTrayIcon = true; #endif return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Persistent"))) { g_persistent = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#SingleInstance"))) { #ifndef MINIDLL g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; // Set default. if (parameter) { if (!_tcsicmp(parameter, _T("Force"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_REPLACE; else if (!_tcsicmp(parameter, _T("Ignore"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_IGNORE; else if (!_tcsicmp(parameter, _T("Off"))) g_AllowOnlyOneInstance = SINGLE_INSTANCE_OFF; } #endif return CONDITION_TRUE; } #ifndef MINIDLL if (IS_DIRECTIVE_MATCH(_T("#InstallKeybdHook"))) { // It seems best not to report this warning because a user may want to use partial functionality // of a script on Win9x: //MsgBox("#InstallKeybdHook is not supported on Windows 95/98/Me. This line will be ignored."); if (!g_os.IsWin9x()) Hotkey::RequireHook(HOOK_KEYBD); return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#InstallMouseHook"))) { // It seems best not to report this warning because a user may want to use partial functionality // of a script on Win9x: //MsgBox("#InstallMouseHook is not supported on Windows 95/98/Me. This line will be ignored."); if (!g_os.IsWin9x()) Hotkey::RequireHook(HOOK_MOUSE); return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#UseHook"))) { g_ForceKeybdHook = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } // L4: Handle #if (expression) directive. if (IS_DIRECTIVE_MATCH(_T("#If"))) { if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off. { g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys. g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it. g_HotWinText = _T(""); // g_HotExprIndex = -1; return CONDITION_TRUE; } Func *currentFunc = g->CurrentFunc; // Ensure variable references are global: g->CurrentFunc = NULL; ConvertEscapeSequences(parameter, g_EscapeChar, false); // Normally done in ParseAndAddLine(). // ACT_EXPRESSION will be changed to ACT_IFEXPR after PreparseBlocks() is called so that EvaluateCondition() // can be used and because ACT_EXPRESSION is designed to discard its result (since it normally would not be // used). This can't be done before PreparseBlocks() is called since this isn't really an IF (it has no body). if (!AddLine(ACT_EXPRESSION, &parameter, UCHAR_MAX + 1)) // UCHAR_MAX signals AddLine to avoid pointing any pending labels or functions at the new line. return FAIL; // Above already displayed the error message. Line *hot_expr_line = mLastLine; // Remove the newly added line from the actual script. if (mFirstLine == mLastLine) mFirstLine = NULL; mLastLine = mLastLine->mPrevLine; if (mLastLine) // Will be NULL if no actual code precedes the #if. mLastLine->mNextLine = NULL; mCurrLine = mLastLine; // Restore to previous value: g->CurrentFunc = currentFunc; // Set the new criterion. g_HotCriterion = HOT_IF_EXPR; // Use the expression text to identify hotkey variants. g_HotWinTitle = hot_expr_line->mArg[0].text; g_HotWinText = _T(""); if (g_HotExprLineCount + 1 > g_HotExprLineCountMax) { // Allocate or reallocate g_HotExprLines. g_HotExprLineCountMax += 100; g_HotExprLines = (Line**)realloc(g_HotExprLines, g_HotExprLineCountMax * sizeof(Line**)); } g_HotExprIndex = g_HotExprLineCount++; g_HotExprLines[g_HotExprIndex] = hot_expr_line; // VicinityToText() assumes lines are linked both ways, so clear mPrevLine in case an error occurs when this line is validated. hot_expr_line->mPrevLine = NULL; // The lines could be linked to simplify function resolution (i.e. allow calling PreparseBlocks() for all lines instead of once for each line) -- However, this would cause confusing/irrelevant vicinity lines to be shown if an error occurs. return CONDITION_TRUE; } // L4: Allow #if timeout to be adjusted. if (IS_DIRECTIVE_MATCH(_T("#IfTimeout"))) { if (parameter) g_HotExprTimeout = ATOU(parameter); return CONDITION_TRUE; } if (!_tcsnicmp(aBuf, _T("#IfWin"), 6)) { bool invert = !_tcsnicmp(aBuf + 6, _T("Not"), 3); if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Active"), 6)) // It matches #IfWin[Not]Active. g_HotCriterion = invert ? HOT_IF_NOT_ACTIVE : HOT_IF_ACTIVE; else if (!_tcsnicmp(aBuf + (invert ? 9 : 6), _T("Exist"), 5)) g_HotCriterion = invert ? HOT_IF_NOT_EXIST : HOT_IF_EXIST; else // It starts with #IfWin but isn't Active or Exist: Don't alter g_HotCriterion. return CONDITION_FALSE; // Indicate unknown directive since there are currently no other possibilities. g_HotExprIndex = -1; // L4: For consistency, don't allow mixing of #if and other #ifWin criterion. if (!parameter) // The omission of the parameter indicates that any existing criteria should be turned off. { g_HotCriterion = HOT_NO_CRITERION; // Indicate that no criteria are in effect for subsequent hotkeys. g_HotWinTitle = _T(""); // Helps maintainability and some things might rely on it. g_HotWinText = _T(""); // return CONDITION_TRUE; } LPTSTR hot_win_title = parameter, hot_win_text; // Set default for title; text is determined later. // Scan for the first non-escaped comma. If there is one, it marks the second parameter: WinText. LPTSTR cp, first_non_escaped_comma; for (first_non_escaped_comma = NULL, cp = hot_win_title; ; ++cp) // Increment to skip over the symbol just found by the inner for(). { for (; *cp && !(*cp == g_EscapeChar || *cp == g_delimiter || *cp == g_DerefChar); ++cp); // Find the next escape char, comma, or %. if (!*cp) // End of string was found. break; #define ERR_ESCAPED_COMMA_PERCENT _T("Literal commas and percent signs must be escaped (e.g. `%)") if (*cp == g_DerefChar) return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf); if (*cp == g_delimiter) // non-escaped delimiter was found. { // Preserve the ability to add future-use parameters such as section of window // over which the mouse is hovering, e.g. #IfWinActive, Untitled - Notepad,, TitleBar if (first_non_escaped_comma) // A second non-escaped comma was found. return ScriptError(ERR_ESCAPED_COMMA_PERCENT, aBuf); // Otherwise: first_non_escaped_comma = cp; continue; // Check if there are any more non-escaped commas. } // Otherwise, an escape character was found, so skip over the next character (if any). if (!*(++cp)) // The string unexpectedly ends in an escape character, so avoid out-of-bounds. break; // Otherwise, the ++cp above has skipped over the escape-char itself, and the loop's ++cp will now // skip over the char-to-be-escaped, which is not the one we want (even if it is a comma). } if (first_non_escaped_comma) // Above found a non-escaped comma, so there is a second parameter (WinText). { // Omit whitespace to (seems best to conform to convention/expectations rather than give // strange whitespace flexibility that would likely cause unwanted bugs due to inadvertently // have two spaces instead of one). The user may use `s and `t to put literal leading/trailing // spaces/tabs into these parameters. hot_win_text = omit_leading_whitespace(first_non_escaped_comma + 1); *first_non_escaped_comma = '\0'; // Terminate at the comma to split off hot_win_title on its own. rtrim(hot_win_title, first_non_escaped_comma - hot_win_title); // Omit whitespace (see similar comment above). // The following must be done only after trimming and omitting whitespace above, so that // `s and `t can be used to insert leading/trailing spaces/tabs. ConvertEscapeSequences() // also supports insertion of literal commas via escaped sequences. ConvertEscapeSequences(hot_win_text, g_EscapeChar, true); } else hot_win_text = _T(""); // And leave hot_win_title set to the entire string because there's only one parameter. // The following must be done only after trimming and omitting whitespace above (see similar comment above). ConvertEscapeSequences(hot_win_title, g_EscapeChar, true); // The following also handles the case where both title and text are blank, which could happen // due to something weird but legit like: #IfWinActive, , if (!SetGlobalHotTitleText(hot_win_title, hot_win_text)) return ScriptError(ERR_OUTOFMEM); // So rare that no second param is provided (since its contents may have been temp-terminated or altered above). return CONDITION_TRUE; } // Above completely handles all directives and non-directives that start with "#IfWin". if (IS_DIRECTIVE_MATCH(_T("#Hotstring"))) { if (parameter) { LPTSTR suboption = tcscasestr(parameter, _T("EndChars")); if (suboption) { // Since it's not realistic to have only a couple, spaces and literal tabs // must be included in between other chars, e.g. `n `t has a space in between. // Also, EndChar \t will have a space and a tab since there are two spaces // after the word EndChar. if ( !(parameter = StrChrAny(suboption, _T("\t "))) ) return CONDITION_TRUE; tcslcpy(g_EndChars, ++parameter, _countof(g_EndChars)); ConvertEscapeSequences(g_EndChars, g_EscapeChar, false); return CONDITION_TRUE; } if (!_tcsnicmp(parameter, _T("NoMouse"), 7)) // v1.0.42.03 { g_HSResetUponMouseClick = false; return CONDITION_TRUE; } // Otherwise assume it's a list of options. Note that for compatibility with its // other caller, it will stop at end-of-string or ':', whichever comes first. Hotstring::ParseOptions(parameter, g_HSPriority, g_HSKeyDelay, g_HSSendMode, g_HSCaseSensitive , g_HSConformToCase, g_HSDoBackspace, g_HSOmitEndChar, g_HSSendRaw, g_HSEndCharRequired , g_HSDetectWhenInsideWord, g_HSDoReset); } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#HotkeyModifierTimeout"))) { if (parameter) g_HotkeyModifierTimeout = ATOI(parameter); // parameter was set to the right position by the above macro return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#HotkeyInterval"))) { if (parameter) { g_HotkeyThrottleInterval = ATOI(parameter); // parameter was set to the right position by the above macro if (g_HotkeyThrottleInterval < 10) // values under 10 wouldn't be useful due to timer granularity. g_HotkeyThrottleInterval = 10; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxHotkeysPerInterval"))) { if (parameter) { g_MaxHotkeysPerInterval = ATOI(parameter); // parameter was set to the right position by the above macro if (g_MaxHotkeysPerInterval < 1) // sanity check g_MaxHotkeysPerInterval = 1; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsPerHotkey"))) { if (parameter) { // Use value as a temp holder since it's int vs. UCHAR and can thus detect very large or negative values: value = ATOI(parameter); // parameter was set to the right position by the above macro if (value > MAX_THREADS_LIMIT) // For now, keep this limited to prevent stack overflow due to too many pseudo-threads. value = MAX_THREADS_LIMIT; // UPDATE: To avoid array overflow, this limit must by obeyed except where otherwise documented. else if (value < 1) value = 1; g_MaxThreadsPerHotkey = value; // Note: g_MaxThreadsPerHotkey is UCHAR. } return CONDITION_TRUE; } #endif if (IS_DIRECTIVE_MATCH(_T("#MaxThreadsBuffer"))) { g_MaxThreadsBuffer = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxThreads"))) { if (parameter) { value = ATOI(parameter); // parameter was set to the right position by the above macro if (value > MAX_THREADS_LIMIT) // For now, keep this limited to prevent stack overflow due to too many pseudo-threads. value = MAX_THREADS_LIMIT; // UPDATE: To avoid array overflow, this limit must by obeyed except where otherwise documented. else if (value < 1) value = 1; g_MaxThreadsTotal = value; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#ClipboardTimeout"))) { if (parameter) g_ClipboardTimeout = ATOI(parameter); // parameter was set to the right position by the above macro return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#LTrim"))) { g_ContinuationLTrim = !parameter || Line::ConvertOnOff(parameter) != TOGGLED_OFF; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#WinActivateForce"))) { g_WinActivateForce = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#ErrorStdOut"))) { mErrorStdOut = true; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MaxMem"))) { if (parameter) { double valuef = ATOF(parameter); // parameter was set to the right position by the above macro if (valuef > 4095) // Don't exceed capacity of VarSizeType, which is currently a DWORD (4 gig). valuef = 4095; // Don't use 4096 since that might be a special/reserved value for some functions. else if (valuef < 1) valuef = 1; g_MaxVarCapacity = (VarSizeType)(valuef * 1024 * 1024); } return CONDITION_TRUE; } #ifndef MINIDLL if (IS_DIRECTIVE_MATCH(_T("#KeyHistory"))) { if (parameter) { g_MaxHistoryKeys = ATOI(parameter); // parameter was set to the right position by the above macro if (g_MaxHistoryKeys < 0) g_MaxHistoryKeys = 0; else if (g_MaxHistoryKeys > 500) g_MaxHistoryKeys = 500; // Above: There are two reasons for limiting the history file to 500 keystrokes: // 1) GetHookStatus() only has a limited size buffer in which to transcribe the keystrokes. // 500 events is about what you would expect to fit in a 32 KB buffer (it the unlikely event // that the transcribed events create too much text, the text will be truncated, so it's // not dangerous anyway). // 2) To reduce the impression that AutoHotkey designed for key logging (the key history file // is in a very unfriendly format that type of key logging anyway). } return CONDITION_TRUE; } #endif // For the below series, it seems okay to allow the comment flag to contain other reserved chars, // such as DerefChar, since comments are evaluated, and then taken out of the game at an earlier // stage than DerefChar and the other special chars. if (IS_DIRECTIVE_MATCH(_T("#CommentFlag"))) { if (parameter) { if (!*(parameter + 1)) // i.e. the length is 1 { // Don't allow '#' since it's the preprocessor directive symbol being used here. // Seems ok to allow "." to be the comment flag, since other constraints mandate // that at least one space or tab occur to its left for it to be considered a // comment marker. if (*parameter == '#' || *parameter == g_DerefChar || *parameter == g_EscapeChar || *parameter == g_delimiter) return ScriptError(ERR_PARAM1_INVALID, aBuf); // Exclude hotkey definition chars, such as ^ and !, because otherwise // the following example wouldn't work: // User defines ! as the comment flag. // The following hotkey would never be in effect since it's considered to // be commented out: // !^a::run,notepad if (*parameter == '!' || *parameter == '^' || *parameter == '+' || *parameter == '$' || *parameter == '~' || *parameter == '*' || *parameter == '<' || *parameter == '>') // Note that '#' is already covered by the other stmt. above. return ScriptError(ERR_PARAM1_INVALID, aBuf); } tcslcpy(g_CommentFlag, parameter, MAX_COMMENT_FLAG_LENGTH + 1); g_CommentFlagLength = _tcslen(g_CommentFlag); // Keep this in sync with above. } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#EscapeChar"))) { if (parameter) { // Don't allow '.' since that can be part of literal floating point numbers: if ( *parameter == '#' || *parameter == g_DerefChar || *parameter == g_delimiter || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_EscapeChar = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#DerefChar"))) { if (parameter) { if ( *parameter == g_EscapeChar || *parameter == g_delimiter || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) // Fix for v1.0.47.05: Allow deref char to be # as documented. return ScriptError(ERR_PARAM1_INVALID, aBuf); g_DerefChar = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Delimiter"))) { // Attempts to change the delimiter to its starting default (comma) are ignored. // For example, "#Delimiter ," isn't meaningful if the delimiter already is a comma, // which is good because "parameter" has already assumed that the comma is accidental // (not a symbol) and omitted it. if (parameter) { if ( *parameter == '#' || *parameter == g_EscapeChar || *parameter == g_DerefChar || *parameter == '.' || (g_CommentFlagLength == 1 && *parameter == *g_CommentFlag) ) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_delimiter = *parameter; } return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#MenuMaskKey"))) { // L38: Allow scripts to specify an alternate "masking" key in place of VK_CONTROL. if (parameter && (g_MenuMaskKey = (BYTE)TextToVK(parameter, NULL, true, true))) return CONDITION_TRUE; else return ScriptError(parameter ? ERR_PARAM1_INVALID : ERR_PARAM1_REQUIRED, aBuf); } if (IS_DIRECTIVE_MATCH(_T("#InputLevel"))) { // All hotkeys declared after this directive are assigned the specified InputLevel. // Input generated at a given SendLevel can only trigger hotkeys that belong to the // same or lower InputLevel. Hotkeys at the lowest level (0) cannot be triggered by // any generated input (the same behavior as AHK versions before this feature). // The default level is 0. int group = parameter ? ATOI(parameter) : 0; if (!SendLevelIsValid(group)) return ScriptError(ERR_PARAM1_INVALID, aBuf); g_InputLevel = group; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#Warn"))) { if (!parameter) parameter = _T("All"); LPTSTR param1_end = _tcschr(parameter, g_delimiter); size_t param1_length = -1; LPTSTR param2 = _T(""); if (param1_end) { param2 = omit_leading_whitespace(param1_end + 1); param1_end = omit_trailing_whitespace(parameter, param1_end - 1); param1_length = param1_end - parameter + 1; } #define IS_PARAM1_MATCH(value) (!tcslicmp(parameter, value, param1_length)) WarnType warnType; if (IS_PARAM1_MATCH(_T("All")) || !param1_length) warnType = WARN_ALL; else if (IS_PARAM1_MATCH(_T("UseUnsetLocal"))) warnType = WARN_USE_UNSET_LOCAL; else if (IS_PARAM1_MATCH(_T("UseUnsetGlobal"))) warnType = WARN_USE_UNSET_GLOBAL; else if (IS_PARAM1_MATCH(_T("UseEnv"))) warnType = WARN_USE_ENV; else if (IS_PARAM1_MATCH(_T("LocalSameAsGlobal"))) warnType = WARN_LOCAL_SAME_AS_GLOBAL; else return ScriptError(ERR_PARAM1_INVALID, aBuf); WarnMode warnMode; if (!*param2) warnMode = WARNMODE_MSGBOX; // omitted mode parameter implies "MsgBox" mode else if (!_tcsicmp(param2, _T("MsgBox"))) warnMode = WARNMODE_MSGBOX; else if (!_tcsicmp(param2, _T("OutputDebug"))) warnMode = WARNMODE_OUTPUTDEBUG; else if (!_tcsicmp(param2, _T("StdOut"))) warnMode = WARNMODE_STDOUT; else if (!_tcsicmp(param2, _T("Off"))) warnMode = WARNMODE_OFF; else return ScriptError(ERR_PARAM2_INVALID, aBuf); if (warnType == WARN_USE_UNSET_LOCAL || warnType == WARN_ALL) g_Warn_UseUnsetLocal = warnMode; if (warnType == WARN_USE_UNSET_GLOBAL || warnType == WARN_ALL) g_Warn_UseUnsetGlobal = warnMode; if (warnType == WARN_USE_ENV || warnType == WARN_ALL) g_Warn_UseEnv = warnMode; if (warnType == WARN_LOCAL_SAME_AS_GLOBAL || warnType == WARN_ALL) g_Warn_LocalSameAsGlobal = warnMode; return CONDITION_TRUE; } if (IS_DIRECTIVE_MATCH(_T("#DllImport"))) { LPTSTR aFuncName = omit_leading_whitespace(parameter); + // backup current function + // Func currentfunc = **g_script.mFunc; if (!*(parameter = _tcschr(parameter,','))) return ScriptError(ERR_PARAM2_REQUIRED, aBuf); else parameter++; *(_tcschr(aFuncName,',')) = '\0'; - + ltrim(parameter); int insert_pos; Func *found_func = FindFunc(aFuncName,_tcslen(aFuncName),&insert_pos); if (found_func) return ScriptError(_T("Duplicate function definition."), aFuncName); // Seems more descriptive than "Function already defined." else if ( !(found_func = AddFunc(aFuncName, _tcslen(aFuncName), false, insert_pos)) ) return FAIL; // It already displayed the error. - found_func->mBIF = (BuiltInFunctionType)BIF_DllImport; //aDynaToken->mfunction; + + // restore previous function + //memcpy(*g_script.mFunc,&currentfunc,sizeof(Func)); + found_func->mBIF = (BuiltInFunctionType)BIF_DllImport; found_func->mIsBuiltIn = true; - - + found_func->mMinParams = 0; + TCHAR buf[MAX_PATH]; size_t space_remaining = LINE_SIZE - (parameter-aBuf); - StrReplace(parameter, _T("%A_ScriptDir%"), mFileDir, SCS_INSENSITIVE, 1, space_remaining); // v1.0.35.11. Caller has ensured string is writable. + if (tcscasestr(parameter, _T("%A_ScriptDir%"))) + { + BIV_ScriptDir(buf, _T("A_ScriptDir")); + StrReplace(parameter, _T("%A_ScriptDir%"), buf, SCS_INSENSITIVE, 1, space_remaining); + } if (tcscasestr(parameter, _T("%A_AppData%"))) // v1.0.45.04: This and the next were requested by Tekl to make it easier to customize scripts on a per-user basis. { BIV_SpecialFolderPath(buf, _T("A_AppData")); StrReplace(parameter, _T("%A_AppData%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AppDataCommon%"))) // v1.0.45.04. { BIV_SpecialFolderPath(buf, _T("A_AppDataCommon")); StrReplace(parameter, _T("%A_AppDataCommon%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_AhkPath%"))) // v1.0.45.04. { BIV_AhkPath(buf, _T("A_AhkPath")); StrReplace(parameter, _T("%A_AhkPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } if (tcscasestr(parameter, _T("%A_DllPath%"))) // v1.0.45.04. { - BIV_AhkPath(buf, _T("A_DllPath")); + BIV_DllPath(buf, _T("A_DllPath")); StrReplace(parameter, _T("%A_DllPath%"), buf, SCS_INSENSITIVE, 1, space_remaining); } - + if (_tcschr(parameter,'%')) + { + return ScriptError(_T("Reference not allowed here, use & where possible. Only %A_AhkPath% %A_DllPath% %A_ScriptDir% %A_AppData[Common]% can be used here."), parameter); + } // terminate dll\function name, find it and jump to next parameter *(_tcschr(parameter,',')) = '\0'; HANDLE func_ptr = (HANDLE)ATOI64(parameter); if (!func_ptr) + { + LPTSTR dll_name = _tcschr(parameter,'\\'); + if (dll_name) + { + *dll_name = '\0'; + if (!GetModuleHandle(parameter)) + LoadLibrary(parameter); + *dll_name = '\\'; + } func_ptr = GetDllProcAddress(parameter); + } if (!func_ptr ) return ScriptError(ERR_NONEXISTENT_FUNCTION, parameter); parameter = parameter + _tcslen(parameter) + 1; LPTSTR parm = SimpleHeap::Malloc(parameter); // If next parameter starts with digit, it is a shift_param definition and is omitted from paramters list for dllcall int aParamCount = ATOI(parm) ? 0 : 1; for(;parameter;aParamCount++) { if (parameter = _tcschr(parameter,',')) parameter++; } if (aParamCount < 2) return ScriptError(ERR_PARAM3_REQUIRED, aBuf); // set max possible parameters for the new function found_func->mParamCount = aParamCount/2; // misuse mGlobalVarCount to hold total amount of parmeters for DllCall - found_func->mGlobalVarCount = aParamCount; + found_func->mLazyVarCount = aParamCount; // allocate memory to hold the parameters and defaults ExprTokenType **func_param = (ExprTokenType**)SimpleHeap::Malloc(aParamCount * sizeof(ExprTokenType*)); ExprTokenType **func_defaults = (ExprTokenType**)SimpleHeap::Malloc(found_func->mParamCount * sizeof(ExprTokenType*)); // misuse mParam to hold default parameters - found_func->mParam = (FuncParam*)func_param; - found_func->mStaticVar = (Var**)func_defaults; + found_func->mStaticVar = (Var**)func_param; + found_func->mStaticLazyVar = (Var**)func_defaults; // assign function pointer func_param[0] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); func_param[0]->symbol = PURE_INTEGER; func_param[0]->value_int64 = (__int64)func_ptr; - + ltrim(parm); // set parameters shift if (ATOI(parm)) { int shift_param[MAX_FUNCTION_PARAMS]; int shift_count = 0; - for (int i;parm && *parm || *parm != ',';parm++) + for (int i;parm && *parm || *parm != ',';) { if (!(i = ATOI(parm))) - break; // next parameter is a string + break; // next parameter is not number shift_param[shift_count] = i*2; parm = StrChrAny(parm,_T("\t ,")); + ltrim(parm); shift_count++; } - if (!parm || !(parm = _tcschr(parm,','))) + if (!parm || !_tcschr(parm,',')) return ScriptError(ERR_PARAM3_REQUIRED, aBuf); - parm++; // adnvance pointer to next parameter since above left a , + if (*parm == ',') + parm++; // adnvance pointer to next parameter since above left a , // fill left parameters order for (int c = 1; shift_count < found_func->mParamCount;c++) { bool found = false; for (int i = 0; i < shift_count || found;i++) found = shift_param[i] == c*2; if (!found) shift_param[shift_count++] = c*2; } - // misuse mGlobalVar, allocate memory and fill shift_param - found_func->mGlobalVar = (Var**)SimpleHeap::Malloc(aParamCount * sizeof(int)); - memcpy(found_func->mGlobalVar,&shift_param,aParamCount * sizeof(int)); + // misuse mLazyVar, allocate memory and fill shift_param + found_func->mLazyVar = (Var**)SimpleHeap::Malloc(aParamCount * sizeof(int)); + memcpy(found_func->mLazyVar,&shift_param,aParamCount * sizeof(int)); } // fill definition and default parameters for ( aParamCount = 1 ; parm ; aParamCount++ ) { + LPTSTR this_parm = parm; + if (parm = _tcschr(parm,',')) + { + *parm = '\0'; + parm++; + } + trim(this_parm); func_param[aParamCount] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); ExprTokenType &this_param = *func_param[aParamCount]; - if (this_param.symbol = IsPureNumeric(parm,true,true,true,true)) + if (this_param.symbol = IsPureNumeric(this_parm,true,true,true,true)) { if (this_param.symbol == PURE_FLOAT) - this_param.value_double = ATOF(parm); + this_param.value_double = ATOF(this_parm); else - this_param.value_int64 = ATOI64(parm); + this_param.value_int64 = ATOI64(this_parm); } else - this_param.marker = parm; + { + if (aParamCount % 2) + { + if (_tcschr(this_parm,'\"') == this_parm && _tcsrchr(this_parm,'\"') == (this_parm + _tcslen(this_parm) - 1)) + { + this_param.marker = ++this_parm; + *(_tcsrchr(this_parm,'\"')) = '\0'; + } + else + this_param.marker = this_parm; + } + else if (_tcschr(this_parm,'\"') == this_parm && _tcsrchr(this_parm,'\"') == (this_parm + _tcslen(this_parm) - 1)) + { + this_param.marker = ++this_parm; + *(_tcsrchr(this_parm,'\"')) = '\0'; + } + else + { // user variable + this_param.var = FindVar(this_parm); + if (!this_param.var) // static variable could not be found + return ScriptError(_T("The variable name contains illegal character or is not declared."), this_parm); + this_param.symbol = SYM_VAR; + } + } if (!(aParamCount % 2)) { func_defaults[aParamCount/2 - 1] = (ExprTokenType*)SimpleHeap::Malloc(sizeof(ExprTokenType)); memcpy(func_defaults[aParamCount/2 - 1],&this_param,sizeof(ExprTokenType)); } - if (parm = _tcschr(parm,',')) - { - *parm = '\0'; - parm++; - } } - return CONDITION_TRUE; } // Otherwise, report that this line isn't a directive: return CONDITION_FALSE; } void ScriptTimer::Disable() { mEnabled = false; --g_script.mTimerEnabledCount; #ifndef MINIDLL if (!g_script.mTimerEnabledCount && !g_nLayersNeedingTimer && !Hotkey::sJoyHotkeyCount) #else if (!g_script.mTimerEnabledCount && !g_nLayersNeedingTimer) #endif KILL_MAIN_TIMER // Above: If there are now no enabled timed subroutines, kill the main timer since there's no other // reason for it to exist if we're here. This is because or direct or indirect caller is // currently always ExecUntil(), which doesn't need the timer while its running except to // support timed subroutines. UPDATE: The above is faulty; Must also check g_nLayersNeedingTimer // because our caller can be one that still needs a timer as proven by this script that // hangs otherwise: //SetTimer, Test, on //Sleep, 1000 //msgbox, done //return //Test: //SetTimer, Test, off //return } ResultType Script::UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable , bool aUpdatePriorityOnly) // Caller should specific a blank aPeriod to prevent the timer's period from being changed // (i.e. if caller just wants to turn on or off an existing timer). But if it does this // for a non-existent timer, that timer will be created with the default period as specified in // the constructor. { ScriptTimer *timer; for (timer = mFirstTimer; timer != NULL; timer = timer->mNextTimer) if (timer->mLabel == aLabel) // Match found. break; bool timer_existed = (timer != NULL); if (!timer_existed) // Create it. { if ( !(timer = new ScriptTimer(aLabel)) ) return ScriptError(ERR_OUTOFMEM); if (!mFirstTimer) mFirstTimer = mLastTimer = timer; else { mLastTimer->mNextTimer = timer; // This must be done after the above: mLastTimer = timer; } ++mTimerCount; } // Update its members: if (aEnable && !timer->mEnabled) // Must check both or the mTimerEnabledCount below will be wrong. { // The exception is if the timer already existed but the caller only wanted its priority changed: if (!(timer_existed && aUpdatePriorityOnly)) { timer->mEnabled = true; ++mTimerEnabledCount; SET_MAIN_TIMER // Ensure the API timer is always running when there is at least one enabled timed subroutine. } //else do nothing, leave it disabled. } else if (!aEnable && timer->mEnabled) // Must check both or the below count will be wrong. timer->Disable(); aPeriod = omit_leading_whitespace(aPeriod); // This causes A_Space to be treated as "omitted" rather than zero, so may change the behaviour of some poorly-written scripts, but simplifies the check below which allows -0 to work. if (*aPeriod) // Caller wanted us to update this member. { __int64 period = ATOI64(aPeriod); if (*aPeriod == '-') // v1.0.46.16: Support negative periods to mean "run only once". { timer->mRunOnlyOnce = true; timer->mPeriod = (DWORD)-period; } else // Positive number. v1.0.36.33: Changed from int to DWORD, and ATOI to ATOU, to double its capacity: { timer->mPeriod = (DWORD)period; // Always use this method & check to retain compatibility with existing scripts. timer->mRunOnlyOnce = false; } } if (*aPriority) // Caller wants this member to be changed from its current or default value. timer->mPriority = ATOI(aPriority); // Read any float in a runtime variable reference as an int. if (!(timer_existed && aUpdatePriorityOnly)) // Caller relies on us updating mTimeLastRun in this case. This is done because it's more // flexible, e.g. a user might want to create a timer that is triggered 5 seconds from now. // In such a case, we don't want the timer's first triggering to occur immediately. // Instead, we want it to occur only when the full 5 seconds have elapsed: timer->mTimeLastRun = GetTickCount(); // Below is obsolete, see above for why: // We don't have to kill or set the main timer because the only way this function is called // is directly from the execution of a script line inside ExecUntil(), in which case: // 1) KILL_MAIN_TIMER is never needed because the timer shouldn't exist while in ExecUntil(). // 2) SET_MAIN_TIMER is never needed because it will be set automatically the next time ExecUntil() // calls MsgSleep(). return OK; } Label *Script::FindLabel(LPTSTR aLabelName) // Returns the first label whose name matches aLabelName, or NULL if not found. // v1.0.42: Since duplicates labels are now possible (to support #IfWin variants of a particular // hotkey or hotstring), callers must be aware that only the first match is returned. // This helps performance by requiring on average only half the labels to be searched before // a match is found. { if (!aLabelName || !*aLabelName) return NULL; for (Label *label = mFirstLabel; label != NULL; label = label->mNextLabel) if (!_tcsicmp(label->mName, aLabelName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return label; // Match found. return NULL; // No match found. } ResultType Script::AddLabel(LPTSTR aLabelName, bool aAllowDupe) // Returns OK or FAIL. { if (!*aLabelName) return FAIL; // For now, silent failure because callers should check this beforehand. if (!aAllowDupe && FindLabel(aLabelName)) // Relies on short-circuit boolean order. // Don't attempt to dereference "duplicate_label->mJumpToLine because it might not // exist yet. Example: // label1: // label1: <-- This would be a dupe-error but it doesn't yet have an mJumpToLine. // return return ScriptError(_T("Duplicate label."), aLabelName); LPTSTR new_name = SimpleHeap::Malloc(aLabelName); if (!new_name) return FAIL; // It already displayed the error for us. Label *the_new_label = new Label(new_name); // Pass it the dynamic memory area we created. if (the_new_label == NULL) return ScriptError(ERR_OUTOFMEM); the_new_label->mPrevLabel = mLastLabel; // Whether NULL or not. if (mFirstLabel == NULL) mFirstLabel = the_new_label; else mLastLabel->mNextLabel = the_new_label; // This must be done after the above: mLastLabel = the_new_label; if (!_tcsicmp(new_name, _T("OnClipboardChange"))) mOnClipboardChangeLabel = the_new_label; return OK; } ResultType Script::ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType, ActionTypeType aOldActionType , LPTSTR aActionName, LPTSTR aEndMarker, LPTSTR aLiteralMap, size_t aLiteralMapLength) // Returns OK or FAIL. // aLineText needs to be a string whose contents are modifiable (though the string won't be made any // longer than it is now, so it doesn't have to be of size LINE_SIZE). This helps performance by // allowing the string to be split into sections without having to make temporary copies. { #ifdef _DEBUG if (!aLineText || !*aLineText) return ScriptError(_T("DEBUG: ParseAndAddLine() called incorrectly.")); #endif TCHAR action_name[MAX_VAR_NAME_LENGTH + 1], *end_marker; if (aActionName) // i.e. this function was called recursively with explicit values for the optional params. { _tcscpy(action_name, aActionName); end_marker = aEndMarker; } else if (aActionType == ACT_EXPRESSION) { *action_name = '\0'; end_marker = NULL; // Indicate that there is no action to mark the end of. } else // We weren't called recursively from self, nor is it ACT_EXPRESSION, so set action_name and end_marker the normal way. { for (;;) // A loop with only one iteration so that "break" can be used instead of a lot of nested if's. { int declare_type; LPTSTR cp; if (!_tcsnicmp(aLineText, _T("Global"), 6)) // Checked first because it's more common than the others. { cp = aLineText + 6; // The character after the declaration word. declare_type = g->CurrentFunc ? VAR_DECLARE_GLOBAL : VAR_DECLARE_SUPER_GLOBAL; } else { if (!g->CurrentFunc) // Not inside a function body, so "Local"/"Static" get no special treatment. break; if (!_tcsnicmp(aLineText, _T("Local"), 5)) { cp = aLineText + 5; // The character after the declaration word. declare_type = VAR_DECLARE_LOCAL; } else if (!_tcsnicmp(aLineText, _T("Static"), 6)) // Static also implies local (for functions that default to global). { cp = aLineText + 6; // The character after the declaration word. declare_type = VAR_DECLARE_STATIC; } else // It's not the word "global", "local", or static, so no further checking is done. break; } if (*cp && !IS_SPACE_OR_TAB(*cp)) // There is a character following the word local but it's not a space or tab. break; // It doesn't qualify as being the global or local keyword because it's something like global2. if (*cp && *(cp = omit_leading_whitespace(cp))) // Probably always a true stmt since caller rtrimmed it, but even if not it's handled correctly. { // Check whether the first character is an operator by seeing if it alone would be a // valid variable name. If it's not valid, this doesn't qualify as the global or local // keyword because it's something like this instead: // local := xyz // local += 3 TCHAR orig_char = cp[1]; cp[1] = '\0'; // Temporarily terminate. ResultType result = Var::ValidateName(cp, DISPLAY_NO_ERROR); cp[1] = orig_char; // Undo the termination. if (!result) // It's probably operator, e.g. local = %var% break; } else // It's the word "global", "local", "static" by itself. But only global or static is valid that way (when it's the first line in the function body). { // All of the following must be checked to catch back-to-back conflicting declarations such // as these: // global x // global ; Should be an error because global vars are implied/automatic. // v1.0.48: Lexikos: Added assume-static mode. For now, this requires "static" to be // placed above local or global variable declarations. if (declare_type != VAR_DECLARE_LOCAL // i.e. VAR_DECLARE_GLOBAL or VAR_DECLARE_STATIC (can't due be VAR_DECLARE_NONE due to checks higher above). && mNextLineIsFunctionBody && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_NONE) { g->CurrentFunc->mDefaultVarType = declare_type; // No further action is required for the word "global" or "static" by itself. return OK; } // Otherwise, it's the word "local" by itself (which isn't allowed since it's the default), // or it's the word global or static by itself, but it occurs too far down in the body. return ScriptError(ERR_UNRECOGNIZED_ACTION, aLineText); // Vague error since so rare. } if (mNextLineIsFunctionBody && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_NONE) { // Both of the above must be checked to catch back-to-back conflicting declarations such // as these: // local x // global y ; Should be an error because global vars are implied/automatic. // This line will become first non-directive, non-label line in the function's body. // If the first non-directive, non-label line in the function's body contains // the "local" keyword, everything inside this function will assume that variables // are global unless they are explicitly declared local (this is the opposite of // the default). The converse is also true. if (declare_type != VAR_DECLARE_STATIC) g->CurrentFunc->mDefaultVarType = declare_type == VAR_DECLARE_LOCAL ? VAR_DECLARE_GLOBAL : VAR_DECLARE_LOCAL; // Otherwise, leave it as-is to allow the following: // static x // local y } else // Since this isn't the first line of the function's body, mDefaultVarType has already been set permanently. { if (g->CurrentFunc && declare_type == g->CurrentFunc->mDefaultVarType) // Can't be VAR_DECLARE_NONE at this point. { // Seems best to flag redundant/unnecessary declarations since they might be an indication // to the user that something is being done incorrectly in this function. This errors also // remind the user what mode the function is in: if (declare_type == VAR_DECLARE_GLOBAL) return ScriptError(_T("Global variables must not be declared in this function."), aLineText); if (declare_type == VAR_DECLARE_LOCAL) return ScriptError(_T("Local variables must not be declared in this function."), aLineText); // In assume-static mode, allow declarations in case they contain initializers. // Would otherwise lose the ability to "initialize only once upon startup". //if (declare_type == VAR_DECLARE_STATIC) // return ScriptError("Static variables must not be declared in this function.", aLineText); } } // Since above didn't break or return, a variable is being declared as an exception to the // mode specified by mDefaultVarType. bool open_brace_was_added, belongs_to_if_or_else_or_loop; size_t var_name_length; LPTSTR item; for (belongs_to_if_or_else_or_loop = mLastLine && ACT_IS_IF_OR_ELSE_OR_LOOP(mLastLine->mActionType) , open_brace_was_added = false, item = cp ; *item;) // FOR EACH COMMA-SEPARATED ITEM IN THE DECLARATION LIST. { LPTSTR item_end = StrChrAny(item, _T(", \t=:")); // Comma, space or tab, equal-sign, colon. if (!item_end) // This is probably the last/only variable in the list; e.g. the "x" in "local x" item_end = item + _tcslen(item); var_name_length = (VarSizeType)(item_end - item); Var *var = NULL; int i; if (g->CurrentFunc) { for (i = 0; i < g->CurrentFunc->mParamCount; ++i) // Search by name to find both global and local declarations. if (!tcslicmp(item, g->CurrentFunc->mParam[i].var->mName, var_name_length)) return ScriptError(_T("Parameters must not be declared."), item); // Detect conflicting declarations: var = FindVar(item, var_name_length, NULL, FINDVAR_LOCAL); if (var && (var->Scope() & ~VAR_DECLARED) == (declare_type & ~VAR_DECLARED) && declare_type != VAR_DECLARE_STATIC) var = NULL; // Allow redeclaration using same scope; e.g. "local x := 1 ... local x := 2" down two different code paths. if (!var && declare_type != VAR_DECLARE_GLOBAL) for (i = 0; i < g->CurrentFunc->mGlobalVarCount; ++i) // Explicitly search this array vs calling FindVar() in case func is assume-global. if (!tcslicmp(g->CurrentFunc->mGlobalVar[i]->mName, item, -1, var_name_length)) { var = g->CurrentFunc->mGlobalVar[i]; break; } if (var) return ScriptError(var->IsDeclared() ? ERR_DUPLICATE_DECLARATION : _T("Declaration conflicts with existing var."), item); } if ( !(var = FindOrAddVar(item, var_name_length, declare_type)) ) return FAIL; // It already displayed the error. if (var->Type() != VAR_NORMAL || !tcslicmp(item, _T("ErrorLevel"), var_name_length)) // Shouldn't be declared either way (global or local). return ScriptError(_T("Built-in variables must not be declared."), item); if (declare_type == VAR_DECLARE_GLOBAL) // Can only be true if g->CurrentFunc is non-NULL. { if (g->CurrentFunc->mGlobalVarCount >= MAX_FUNC_VAR_GLOBALS) return ScriptError(_T("Too many declarations."), item); // Short message since it's so unlikely. g->CurrentFunc->mGlobalVar[g->CurrentFunc->mGlobalVarCount++] = var; } else if (declare_type == VAR_DECLARE_SUPER_GLOBAL) { // Ensure the "declared" and "super-global" flags are set, in case this // var was added to the list via a reference prior to the declaration. var->Scope() = declare_type; } item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'. bool convert_the_operator; switch(*item_end) { case ',': // No initializer is present for this variable, so move on to the next one. item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration. continue; // No further processing needed below. case '\0': // No initializer is present for this variable, so move on to the next one. item = item_end; // Set "item" for use by the next iteration. continue; case ':': if (item_end[1] != '=') // Colon with no following '='. return ScriptError(ERR_UNRECOGNIZED_ACTION, item); // Vague error since so rare. item_end += 2; // Point to the character after the ":=". convert_the_operator = false; break; case '=': // Here '=' is clearly an assignment not a comparison, so further below it will be converted to := ++item_end; // Point to the character after the "=". convert_the_operator = true; break; default: // L31: This can be reached by something not officially supported like "global var .= value_to_append". // In previous versions, convert_the_operator was left uninitialized and whether it would work or be // replaced with ".:=" and fail was up to chance. (Testing showed it failed only in Debug mode.) convert_the_operator = false; } LPTSTR right_side_of_operator = item_end; // Save for use by VAR_DECLARE_STATIC below. // Since above didn't "continue", this declared variable also has an initializer. // Add that initializer as a separate line to be executed at runtime. Separate lines // might actually perform better at runtime because most initializers tend to be simple // literals or variables that are simplified into non-expressions at runtime. In addition, // items without an initializer are omitted, further improving runtime performance. // However, the following must be done ONLY after having done the FindOrAddVar() // above, since that may have changed this variable to a non-default type (local or global). // But what about something like "global x, y=x"? Even that should work as long as x // appears in the list prior to initializers that use it. // Now, find the comma (or terminator) that marks the end of this sub-statement. // The search must exclude commas that are inside quoted/literal strings and those that // are inside parentheses (chiefly those of function-calls, but possibly others). item_end += FindNextDelimiter(item_end); // FIND THE NEXT "REAL" COMMA (or the end of the string). // Above has now found the final comma of this sub-statement (or the terminator if there is no comma). LPTSTR terminate_here = omit_trailing_whitespace(item, item_end-1) + 1; // v1.0.47.02: Fix the fact that "x=5 , y=6" would preserve the whitespace at the end of "5". It also fixes wrongly showing a syntax error for things like: static d="xyz" , e = 5 TCHAR orig_char = *terminate_here; *terminate_here = '\0'; // Temporarily terminate (it might already be the terminator, but that's harmless). if (declare_type == VAR_DECLARE_STATIC) { LPTSTR args[] = {var->mName, ConvertEscapeSequences(omit_leading_whitespace(right_side_of_operator), g_EscapeChar, false)}; // UCHAR_MAX signals AddLine to avoid pointing any pending labels or functions at the new line. // Otherwise, ParseAndAddLine could be used like in the section below to optimize simple // assignments, but that would be nearly pointless for static initializers anyway: if (!AddLine(ACT_ASSIGNEXPR, args, UCHAR_MAX + 2)) return FAIL; // Above already displayed the error. mLastLine = mLastLine->mPrevLine; // Restore mLastLine to the last non-'static' line, but leave mCurrLine set to the new line. mLastLine->mNextLine = NULL; // Remove the new line from the main script's linked list of lines. For maintainability: AddLine() unconditionally overwrites mLastLine->mNextLine anyway. if (mLastStaticLine) mLastStaticLine->mNextLine = mCurrLine; else mFirstStaticLine = mCurrLine; mCurrLine->mPrevLine = mLastStaticLine; // Even if NULL. Must be set otherwise VicinityToText() will show the wrong line if this one or one "near" it has an error. mLastStaticLine = mCurrLine; // Some of the checks below could be used to "optimize" static initializers, but since they // will only be executed once each anyway, it doesn't seem useful. Making them expressions // should be overall more consistent and saves worrying about cases like the following, // which previously gave unexpected results: static var := "literal" . "literal" /* // The following is similar to the code used to support default values for function parameters. // So maybe maintain them together. right_side_of_operator = omit_leading_whitespace(right_side_of_operator); if (!_tcsicmp(right_side_of_operator, _T("false"))) var->Assign(_T("0")); else if (!_tcsicmp(right_side_of_operator, _T("true"))) var->Assign(_T("1")); else // The only other supported initializers are "string", integers, and floats. { // Vars could be supported here via FindVar(), but only globals ABOVE this point in // the script would be supported (since other globals don't exist yet; in fact, even // those that do exist don't have any contents yet, so it would be pointless). So it // seems best to wait until full/comprehensive support for expressions is // studied/designed for both statics and parameter-default-values. if (*right_side_of_operator == '"' && terminate_here[-1] == '"') // Quoted/literal string. { ++right_side_of_operator; // Omit the opening-quote from further consideration. terminate_here[-1] = '\0'; // Remove the close-quote from further consideration. ConvertEscapeSequences(right_side_of_operator, g_EscapeChar, false); // Raw escape sequences like `n haven't been converted yet, so do it now. // Convert all pairs of quotes into single literal quotes: StrReplace(right_side_of_operator, _T("\"\""), _T("\""), SCS_SENSITIVE); } else // It's not a quoted string (nor the empty string); or it has a missing ending quote (rare). { if (!IsPureNumeric(right_side_of_operator, true, false, true)) // It's not a number, and since we're here it's not a quoted/literal string either. return ScriptError(_T("Unsupported static initializer."), right_side_of_operator); //else it's an int or float, so just assign the numeric string itself (there // doesn't seem to be any need to convert it to float/int first, though that would // make things more consistent such as storing .1 as 0.1). } if (*right_side_of_operator) // It can be "" in cases such as "" being specified literally in the script, in which case nothing needs to be done because all variables start off as "". var->Assign(right_side_of_operator); } */ } else // A non-static initializer, so a line of code must be produced that will be executed at runtime every time the function is called. { // PERFORMANCE: As of v1.0.48 (with cached binary numbers and pre-postfixed expressions), // assignments of literal integers to variables are up to 10% slower when done as a combined // (comma-separated) expression rather than each as a separate line. However, this slowness // eventually disappears and may even reverse as more and more such expressions are combined // into a single expression (e.g. the following is almost the same speed either way: // x:=1,y:=22,z:=333,a:=4444,b:=55555). By contrast, assigning a literal string, another // variable, or a complex expression is the opposite: they are always faster when done via // commas, and they continue to get faster and faster as more expressions are merged into a // single comma-separated expression. In light of this, a future version could combine ONLY // those declarations that have initializers into a single comma-separately expression rather // than making a separate expression for each. However, since it's not always faster to do // so (e.g. x:=0,y:=1 is faster as separate statements), and since it is somewhat rare to // have a long chain of initializers, and since these performance differences are documented, // it might not be worth changing. LPTSTR line_to_add; TCHAR new_buf[LINE_SIZE]; // Declared outside the braces below so that it stays in scope long enough. Using so much stack space here and in caller seems unlikely to affect performance, so _alloca seems unlikely to help. if (convert_the_operator) // Convert first '=' in item to be ":=". { // Prevent any chance of overflow by using new_buf (overflow might otherwise occur in cases // such as this sub-statement being the very last one in the declaration list, and being // at the limit of the buffer's capacity). StrReplace(_tcscpy(new_buf, item), _T("="), _T(":="), SCS_SENSITIVE, 1); // Can't overflow because there's only one replacement and we know item's length can't be that close to the capacity limit. line_to_add = new_buf; } else line_to_add = item; if (belongs_to_if_or_else_or_loop && !open_brace_was_added) // v1.0.46.01: Put braces to allow initializers to work even directly under an IF/ELSE/LOOP. Note that the braces aren't added or needed for static initializers. { if (!AddLine(ACT_BLOCK_BEGIN)) return FAIL; open_brace_was_added = true; } // Call Parse() vs. AddLine() because it detects and optimizes simple assignments into // non-expressions for faster runtime execution. if (!ParseAndAddLine(line_to_add)) // For simplicity and maintainability, call self rather than trying to set things up properly to stay in self. return FAIL; // Above already displayed the error. } *terminate_here = orig_char; // Undo the temporary termination. // Set "item" for use by the next iteration: item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list. ? omit_leading_whitespace(item_end + 1) : item_end; // It's the terminator, so let the loop detect that to finish. } // for() each item in the declaration list. if (open_brace_was_added) if (!AddLine(ACT_BLOCK_END)) return FAIL; return OK; } // single-iteration for-loop // Since above didn't return, it's not a declaration such as "global MyVar". if ( !(end_marker = ParseActionType(action_name, aLineText, true)) ) return FAIL; // It already displayed the error. } // Above has ensured that end_marker is the address of the last character of the action name, // or NULL if there is no action name. // Find the arguments (not to be confused with exec_params) of this action, if it has any: LPTSTR action_args; bool could_be_named_action; if (end_marker) { action_args = omit_leading_whitespace(end_marker + 1); // L34: Require that named commands and their args are delimited with a space, tab or comma. diff --git a/source/script2.cpp b/source/script2.cpp index f5eec17..d9b044b 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -13668,1048 +13668,1048 @@ CStringW **pStr = (CStringW **) // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParamCount > 1 && aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters IObject *paramobj = ((aParam[1]->symbol == SYM_OBJECT) ? aParam[1]->object : aParam[1]->var->mObject); oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); paramobj->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. if (result_token.value_int64 < 2) { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } else { obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; paramobj->Invoke(result_token,*aParam[1],IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } else { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; if (is_call && aParam[0]->symbol == SYM_OPERAND && _tcscmp(aParam[0]->marker,_T(""))) { ConvertDllArgType(&aParam[0]->marker, return_attrib); } // Set default dynacall parameters for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) break; ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DynaCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = is_call; i < aParamCount; ++arg_count, i += 1) // Same loop as used in above, so maintain them together. { ExprTokenType &this_param = *aParam[i]; // Resolved for performance and convenience. // The following check applies to DLL_ARG_xSTR, which is "AStr" on Unicode builds and "WStr" // on ANSI builds. Since the buffer is only as large as required to hold the input string, // it has very limited use as an output parameter. Thus, it seems best to ignore anything the // function may have written into the buffer (primarily for performance), and just delete it: if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[arg_count+1] : arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } return OK; } BIF_DECL(BIF_DllImport) // #DllImport will create a dummy function that will redirect the call here // All parameters are pre-defined in func-> structure and are used to call the Dll function via DllCall { Func *func = g_script.FindFunc(aResultToken.marker); - int *shift_param = (int*)func->mGlobalVar; - int param_count = func->mGlobalVarCount; - ExprTokenType **func_param = (ExprTokenType **)func->mParam; - ExprTokenType **default_param = (ExprTokenType **)func->mStaticVar; + int *shift_param = (int*)func->mLazyVar; + int param_count = func->mLazyVarCount; + ExprTokenType **func_param = (ExprTokenType **)func->mStaticVar; + ExprTokenType **default_param = (ExprTokenType **)func->mStaticLazyVar; if (shift_param) { // apply default paramters first for (int c = 0,i = 2;i < param_count;i+=2,c++) { func_param[i] = default_param[c]; } // now put passed parameters in correct place (defined by shift_param) for (int i = 0;i < aParamCount;i++) { if (aParam[i]->symbol != SYM_MISSING) func_param[shift_param[i]] = aParam[i]; } } else { // if a parameter was passed, apply it, otherwise apply default parameter for (int c = 0,i = 2;i < param_count;i+=2,c++) { - func_param[i] = (aParamCount >= i/2 && aParam[c]->symbol != SYM_MISSING) ? aParam[c] : default_param[c]; + func_param[i] = (aParamCount > c && aParam[c]->symbol != SYM_MISSING) ? aParam[c] : default_param[c]; } } BIF_DllCall(aResult,aResultToken,func_param,param_count); } BIF_DECL(BIF_DllCall) // Stores a number or a SYM_STRING result in aResultToken. // Sets ErrorLevel to the error code appropriate to any problem that occurred. // 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) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); HMODULE hmodule_to_free = NULL; // Set default in case of early goto; mostly for maintainability. void *function; // Will hold the address of the function to be called. // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch(aParam[0]->symbol) { case SYM_STRING: // By far the most common, so it's listed first for performance. Also for performance, don't even consider the possibility that a quoted literal string like "33" is a function-address. function = NULL; // Indicate that no function has been specified yet. break; case SYM_VAR: // 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 = (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) ? (void *)aParam[0]->var->ToInt64(TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. // 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 ErrorLevel of 0xc0000005. //if (temp64 <= 0) //{ // g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. // return; //} //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: case SYM_MISSING: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; LPTSTR return_type_string[2]; switch (token.symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. break; case SYM_STRING: case SYM_OPERAND: return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. break; default: return_type_string[0] = _T(""); // It will be detected as invalid below. return_type_string[1] = NULL; break; } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { switch (aParam[i]->symbol) { case SYM_VAR: // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). break; case SYM_STRING: case SYM_OPERAND: arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; // Added in 1.0.48. break; default: arg_type_string[0] = _T(""); // It will be detected as invalid below. arg_type_string[1] = NULL; break; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: if (aParam[i]->symbol == SYM_VAR) aParam[i]->var->MaybeWarnUninitialized(); g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(TokenToString(*aParam[0]), &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above.
tinku99/ahkdll
34c374b1a0d7ac7da675bc9f7bb7f01ee71fec1e
Fixed DynaCall when function = 0
diff --git a/source/script2.cpp b/source/script2.cpp index 8d70b0e..f5eec17 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -13044,1025 +13044,1025 @@ DYNARESULT DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD & #ifdef WIN32_PLATFORM esp_delta = esp_start - esp_end; // Positive number means too many args were passed, negative means too few. if (esp_delta && (aFlags & DC_CALL_STD)) { *buf = 'A'; // The 'A' prefix indicates the call was made, but with too many or too few args. _itot(esp_delta, buf + 1, 10); g_script.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Assign buf not _itot()'s return value, which is the wrong location. } 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.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Positive ErrorLevel numbers are reserved for exception codes. } else g_ErrorLevel->Assign(ERRORLEVEL_NONE); return Res; } void ConvertDllArgType(LPTSTR aBuf[], DYNAPARM &aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[32]; int i; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf[0]; i < 2 && type_string; type_string = aBuf[++i]) { 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) { // The following also serves to set the default in case this is the first iteration. // Set default but perform second iteration in case the second type string isn't NULL. // In other words, if the second type string is explicitly valid rather than blank, // it should override the following default: aDynaParam.type = DLL_ARG_INVALID; // To assist with detection of errors like DllCall(...,flaot,n), treat empty string as an error; naked "CDecl" is now handled elsewhere. OBSOLETE COMMENT: Assume int. This is relied upon at least for having a return type such as a naked "CDecl". continue; // OK to do this regardless of whether this is the first or second iteration. } tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below. // v1.0.30.02: The addition of 'P' allows the quotes to be omitted around a pointer type. // However, the current detection below relies upon the fact that not 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; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsicmp(buf, _T(t))) aDynaParam.type = (n); TEST_TYPE("Int", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("Str", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("Ptr", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("Ptr", DLL_ARG_INT) #endif TEST_TYPE("Short", DLL_ARG_SHORT) TEST_TYPE("Char", DLL_ARG_CHAR) TEST_TYPE("Int64", DLL_ARG_INT64) TEST_TYPE("Float", DLL_ARG_FLOAT) TEST_TYPE("Double", DLL_ARG_DOUBLE) TEST_TYPE("AStr", DLL_ARG_ASTR) TEST_TYPE("WStr", DLL_ARG_WSTR) TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. { if (i > 0) // Second iteration. { // Reset flags to go with any blank value (i.e. !*buf) we're falling back to from the first iteration // (in case our iteration changed the flags based on bogus contents of the second type_string): aDynaParam.passed_by_address = false; aDynaParam.is_unsigned = false; //aDynaParam.type: The first iteration already set it to DLL_ARG_INT or DLL_ARG_INVALID. } else // First iteration, so aDynaParam.type's value will be set by the second (however, the loop's own condition will skip the second iteration if the second type_string is NULL). { aDynaParam.type = DLL_ARG_INVALID; // Set in case of: 1) the second iteration is skipped by the loop's own condition (since the caller doesn't always initialize "type"); or 2) the second iteration can't find a valid type. continue; } } // Since above didn't "continue", the type is explicitly valid so "return" to ensure that // the second iteration doesn't run (in case this is the first iteration): return; } } int ConvertDllArgTypes(LPTSTR aBuf, DYNAPARM *aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[1024]; int i; int arg_count = 0; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf; *type_string; type_string = (aBuf + (++i))) { if (_tcschr(type_string,'=') || _tcschr(type_string,' ') || _tcschr(type_string,'\t') || ctoupper(*type_string) == 'U' || (*type_string == '*') ) continue; if (i>0 && ctoupper(*(aBuf + i - 1)) == 'U') // Unsigned aDynaParam[arg_count].is_unsigned = true; else aDynaParam[arg_count].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) break; tcslcpy(buf, type_string+1, 2); // Make a modifiable copy for easier parsing below. if (StrChrAny(buf, _T("*pP"))) // Additional validation: ensure nothing following the suffix. aDynaParam[arg_count].passed_by_address = true; else aDynaParam[arg_count].passed_by_address = false; tcslcpy(buf, type_string, 2); // Make a modifiable copy for easier parsing below. if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(buf, _T(t), 1)) aDynaParam[arg_count].type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. break; arg_count++; } return arg_count; } bool IsDllArgTypeName(LPTSTR name) // Test whether given name is a valid DllCall arg type (used by Script::MaybeWarnLocalSameAsGlobal). { LPTSTR names[] = { name, NULL }; DYNAPARM param; // An alternate method using an array of strings and tcslicmp in a loop benchmarked // slightly faster than this, but didn't seem worth the extra code size. This should // be more maintainable and is guaranteed to be consistent with what DllCall accepts. ConvertDllArgType(names, param); return param.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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } BIF_DECL(BIF_DynaCall) { IObject *obj = TokenToObject(*aParam[0]); if (obj) { obj->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); return; } else if (aParamCount == 1 && aParam[0]->symbol == PURE_INTEGER) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // DynaToken *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; DYNAPARM *dyna_param; ExprTokenType token; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (aParamCount > 1) { if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; if (aParam[1]->symbol == SYM_OBJECT) aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); else aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string = token.var->Contents(TRUE,TRUE); } else { return_type_string = token.marker; } int i = 0; for (;return_type_string[i];i++) { if ( !(_tcschr(return_type_string+i,'=') || ctoupper(return_type_string[i]) == 'U' || ctoupper(return_type_string[i]) == 'P' || (return_type_string[i] == '*')) )// Unsigned obj->marg_count++; } dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string,dyna_param)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string,'=')) { #ifdef WIN32_PLATFORM if (_tcschr((_tcschr(return_type_string,'=') + 1),'=')) obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR return_type_arg[4]; // maximal length of return type + terminating character int c = 0; for (i = 0, c = 0;_tcschr(return_type_string + c + 1,'=');c++) { if (return_type_string[c] != ' ' && return_type_string[c] != '/t') return_type_arg[i++] = return_type_string[c]; } return_type_arg[i] = '\0'; if (StrChrAny(return_type_arg, _T("uU"))) { _tcsncpy(return_type_arg,return_type_arg + 1,sizeof(TCHAR) * 2); obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(return_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(return_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } #ifdef WIN32_PLATFORM if (!obj->mreturn_attrib.passed_by_address) // i.e. the special return flags below are not needed when an address is being returned. { if (obj->mreturn_attrib.type == DLL_ARG_DOUBLE) obj->mdll_call_mode |= DC_RETVAL_MATH8; else if (obj->mreturn_attrib.type == DLL_ARG_FLOAT) obj->mdll_call_mode |= DC_RETVAL_MATH4; } #endif } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) - obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); + obj->mfunction = GetDllProcAddress(TokenToString(*aParam[0]), NULL); if (!obj->mfunction) { g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DynaCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } // allocate memory for parameters and default parameters // in current design we need to have mdefault_param to be initialized // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); int i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before passing a buffer 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 (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParamCount > 1 && aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters IObject *paramobj = ((aParam[1]->symbol == SYM_OBJECT) ? aParam[1]->object : aParam[1]->var->mObject); oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); paramobj->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. if (result_token.value_int64 < 2) { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } else { obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; paramobj->Invoke(result_token,*aParam[1],IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } else { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; if (is_call && aParam[0]->symbol == SYM_OPERAND && _tcscmp(aParam[0]->marker,_T(""))) { ConvertDllArgType(&aParam[0]->marker, return_attrib); } // Set default dynacall parameters for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) break; ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DynaCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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;
tinku99/ahkdll
96dbbbd0bb92041187f8e2232e811a1dd25ed6f4
Fix Alias() if alias variable is object
diff --git a/source/Debugger.cpp b/source/Debugger.cpp index 4ae69ca..2d6a470 100644 --- a/source/Debugger.cpp +++ b/source/Debugger.cpp @@ -2252,517 +2252,517 @@ int Debugger::Disconnect() // void Debugger::Exit(ExitReasons aExitReason, char *aCommandName) { if (mSocket == INVALID_SOCKET) return; // Don't care if it fails as we may be exiting due to a previous failure. SendContinuationResponse(aCommandName, "stopped", aExitReason == EXIT_ERROR ? "error" : "ok"); Disconnect(); } int Debugger::FatalError(LPCTSTR aMessage) { g_Debugger.Disconnect(); if (IDNO == MessageBox(g_hWnd, aMessage, g_script.mFileSpec, MB_YESNO | MB_ICONSTOP | MB_SETFOREGROUND | MB_APPLMODAL)) { // The following will exit even if the OnExit subroutine does not use ExitApp: g_script.ExitApp(EXIT_ERROR, _T("")); } return DEBUGGER_E_INTERNAL_ERROR; } const char *Debugger::sBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; #define BINARY_TO_BASE64_CHAR(b) (sBase64Chars[(b) & 63]) #define BASE64_CHAR_TO_BINARY(q) (strchr(sBase64Chars, q)-sBase64Chars) // Encode base 64 data. size_t Debugger::Base64Encode(char *aBuf, const char *aInput, size_t aInputSize/* = -1*/) { UINT_PTR buffer; size_t i, len = 0; if (aInputSize == -1) // Direct comparison since aInputSize is unsigned. aInputSize = strlen(aInput); for (i = aInputSize; i > 2; i -= 3) { buffer = (UCHAR)aInput[0] << 16 | (UCHAR)aInput[1] << 8 | (UCHAR)aInput[2]; // L39: Fixed for chars outside the range 0..127. [thanks jackieku] aInput += 3; aBuf[len + 0] = BINARY_TO_BASE64_CHAR(buffer >> 18); aBuf[len + 1] = BINARY_TO_BASE64_CHAR(buffer >> 12); aBuf[len + 2] = BINARY_TO_BASE64_CHAR(buffer >> 6); aBuf[len + 3] = BINARY_TO_BASE64_CHAR(buffer); len += 4; } if (i > 0) { buffer = (UCHAR)aInput[0] << 16; if (i > 1) buffer |= (UCHAR)aInput[1] << 8; // aInput not incremented as it is not used below. aBuf[len + 0] = BINARY_TO_BASE64_CHAR(buffer >> 18); aBuf[len + 1] = BINARY_TO_BASE64_CHAR(buffer >> 12); aBuf[len + 2] = (i > 1) ? BINARY_TO_BASE64_CHAR(buffer >> 6) : '='; aBuf[len + 3] = '='; len += 4; } aBuf[len] = '\0'; return len; } // Decode base 64 data. aBuf and aInput may point to the same buffer. size_t Debugger::Base64Decode(char *aBuf, const char *aInput, size_t aInputSize/* = -1*/) { UINT_PTR buffer; size_t i, len = 0; if (aInputSize == -1) // Direct comparison since aInputSize is unsigned. aInputSize = strlen(aInput); while (aInputSize > 0 && aInput[aInputSize-1] == '=') --aInputSize; for (i = aInputSize; i > 3; i -= 4) { buffer = BASE64_CHAR_TO_BINARY(aInput[0]) << 18 // L39: Fixed bad reliance on order of *side-effects++. [thanks fincs] | BASE64_CHAR_TO_BINARY(aInput[1]) << 12 | BASE64_CHAR_TO_BINARY(aInput[2]) << 6 | BASE64_CHAR_TO_BINARY(aInput[3]); aInput += 4; aBuf[len + 0] = (buffer >> 16) & 255; aBuf[len + 1] = (buffer >> 8) & 255; aBuf[len + 2] = buffer & 255; len += 3; } if (i > 1) { buffer = BASE64_CHAR_TO_BINARY(aInput[0]) << 18 | BASE64_CHAR_TO_BINARY(aInput[1]) << 12; if (i > 2) buffer |= BASE64_CHAR_TO_BINARY(aInput[2]) << 6; // aInput not incremented as it is not used below. aBuf[len++] = (buffer >> 16) & 255; if (i > 2) aBuf[len++] = (buffer >> 8) & 255; } aBuf[len] = '\0'; return len; } // // class Debugger::Buffer - simplifies memory management. // // Write data into the buffer, expanding it as necessary. int Debugger::Buffer::Write(char *aData, size_t aDataSize) { if (mFailed) // See WriteF() for comments. return DEBUGGER_E_INTERNAL_ERROR; if (aDataSize == -1) aDataSize = strlen(aData); if (aDataSize == 0) return DEBUGGER_E_OK; if (ExpandIfNecessary(mDataUsed + aDataSize) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; memcpy(mData + mDataUsed, aData, aDataSize); mDataUsed += aDataSize; return DEBUGGER_E_OK; } // Write formatted data into the buffer. Supports %s (char*), %e (char*, "&'<> escaped), %i (int), %u (unsigned int), %p (UINT_PTR). int Debugger::Buffer::WriteF(const char *aFormat, ...) { if (mFailed) { // A prior Write() failed and the now-invalid data hasn't yet been cleared // from the buffer. Abort. This allows numerous other parts of the code // to omit error-checking. return DEBUGGER_E_INTERNAL_ERROR; } int i; size_t len; char c; const char *format_ptr, *s, *param_ptr, *entity; char number_buf[MAX_INTEGER_SIZE]; va_list vl; for (len = 0, i = 0; i < 2; ++i) { va_start(vl, aFormat); // Calculate the required buffer size. for (format_ptr = aFormat; c = *format_ptr; ++format_ptr) { if (c == '%') { switch (format_ptr[1]) { case 's': s = va_arg(vl, char*); break; case 'i': s = _itoa(va_arg(vl, int), number_buf, 10); break; case 'u': s = _ultoa(va_arg(vl, unsigned long), number_buf, 10); break; case 'p': s = Exp32or64(_ultoa,_ui64toa)(va_arg(vl, UINT_PTR), number_buf, 10); break; case 'e': // String, replace "&'<> with appropriate XML entity. { s = va_arg(vl, char*); if (i == 0) { for (param_ptr = s; *param_ptr; ++param_ptr) { switch (*param_ptr) { case '"': case '\'': len += 6; break; // &quot; or &apos; case '&': len += 5; break; // &amp; case '<': case '>': len += 4; break; // &lt; or &gt; default: ++len; } } } else { for (param_ptr = s; c = *param_ptr; ++param_ptr) { switch (c) { case '"': entity = "quot"; break; case '\'': entity = "apos"; break; case '&': entity = "amp"; break; case '<': entity = "lt"; break; case '>': entity = "gt"; break; default: mData[mDataUsed++] = c; continue; } // One of: "'&<> - entity is set to the appropriate entity name. mDataUsed += sprintf(mData + mDataUsed, "&%s;", entity); } } ++format_ptr; // Skip %, outer loop will skip format char. //s = NULL; // Skip section below. //break; continue; } default: s = NULL; // Skip section below. } // switch (format_ptr[1]) if (s) { // %s, %i or %u. if (i == 0) { // Calculate required buffer space on first iteration. len += strlen(s); } else if (len = strlen(s)) { // Write into buffer on second iteration. // memcpy as we don't want the terminating null character. memcpy(mData + mDataUsed, s, len); mDataUsed += len; } ++format_ptr; // Skip %, outer loop will skip format char. continue; } } // if (c == '%') // Count or copy character as is. if (i == 0) ++len; else mData[mDataUsed++] = *format_ptr; } // for (format_ptr = aFormat; c = *format_ptr; ++format_ptr) if (i == 0) if (ExpandIfNecessary(mDataUsed + len) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; } // for (len = 0, i = 0; i < 2; ++i) return DEBUGGER_E_OK; } // Convert a file path to a URI and write it to the buffer. int Debugger::Buffer::WriteFileURI(const char *aPath) { int c, len = 9; // 8 for "file:///", 1 for '\0' (written by sprintf()). // Calculate required buffer size for path after encoding. for (const char *ptr = aPath; c = *ptr; ++ptr) { if (cisalnum(c) || strchr("-_.!~*'()/\\", c)) ++len; else len += 3; } // Ensure the buffer contains enough space. if (ExpandIfNecessary(mDataUsed + len) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; Write("file:///", 8); // Write to the buffer, encoding as we go. for (const char *ptr = aPath; c = *ptr; ++ptr) { if (cisalnum(c) || strchr("-_.!~*()/", c)) { mData[mDataUsed++] = (char)c; } else if (c == '\\') { // This could be encoded as %5C, but it's more readable this way: mData[mDataUsed++] = '/'; } else { len = sprintf(mData + mDataUsed, "%%%02X", c & 0xff); if (len != -1) mDataUsed += len; } } return DEBUGGER_E_OK; } int Debugger::Buffer::WriteEncodeBase64(const char *aInput, size_t aInputSize, bool aSkipBufferSizeCheck/* = false*/) { if (aInputSize) { if (!aSkipBufferSizeCheck) { // Ensure required buffer space is available. if (ExpandIfNecessary(mDataUsed + DEBUGGER_BASE64_ENCODED_SIZE(aInputSize)) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; } //else caller has already ensured there is enough space and wants to be absolutely sure mData isn't reallocated. ASSERT(mDataUsed + aInputSize < mDataSize); if (aInput) mDataUsed += Debugger::Base64Encode(mData + mDataUsed, aInput, aInputSize); //else caller wanted to reserve some buffer space, probably to read the raw data into. } //else there's nothing to write, just return OK. Calculations above can't handle (size_t)0 return DEBUGGER_E_OK; } // Decode a file URI in-place. void Debugger::DecodeURI(char *aUri) { char *end = strchr(aUri, 0); char escape[3]; escape[2] = '\0'; if (!strnicmp(aUri, "file:///", 8)) { // Use memmove since I'm not sure if strcpy can handle overlap. end -= 8; memmove(aUri, aUri + 8, end - aUri); } // Some debugger UI's use file://path even though it is invalid (it should be file:///path or file://server/path). // For compatibility with these UI's, support file://. else if (!strnicmp(aUri, "file://", 7)) { end -= 7; memmove(aUri, aUri + 7, end - aUri); } char *dst, *src; for (src = dst = aUri; src < end; ++src, ++dst) { if (*src == '%' && src + 2 < end) { escape[0] = *++src; escape[1] = *++src; *dst = (char)strtol(escape, NULL, 16); } else if (*src == '/') *dst = '\\'; else *dst = *src; } *dst = '\0'; } // Initialize or expand the buffer, don't care how much. int Debugger::Buffer::Expand() { return ExpandIfNecessary(mDataSize ? mDataSize * 2 : DEBUGGER_INITIAL_BUFFER_SIZE); } // Expand as necessary to meet a minimum required size. int Debugger::Buffer::ExpandIfNecessary(size_t aRequiredSize) { if (mFailed) return DEBUGGER_E_INTERNAL_ERROR; size_t new_size; for (new_size = mDataSize ? mDataSize : DEBUGGER_INITIAL_BUFFER_SIZE ; new_size < aRequiredSize ; new_size *= 2); if (new_size > mDataSize) { // For simplicity, this preserves all of mData not just the first mDataUsed bytes. Some sections may rely on this. char *new_data = (char*)realloc(mData, new_size); if (new_data == NULL) { mFailed = TRUE; return DEBUGGER_E_INTERNAL_ERROR; } mData = new_data; mDataSize = new_size; } return DEBUGGER_E_OK; } // Remove data from the front of the buffer (i.e. after it is processed). void Debugger::Buffer::Remove(size_t aDataSize) { ASSERT(aDataSize <= mDataUsed); // Move remaining data to the front of the buffer. if (aDataSize < mDataUsed) memmove(mData, mData + aDataSize, mDataUsed - aDataSize); mDataUsed -= aDataSize; } void Debugger::Buffer::Clear() { mDataUsed = 0; mFailed = FALSE; } DbgStack::Entry *DbgStack::Push() { if (mTop == mTopBound) Expand(); if (mTop >= mBottom) { // Whenever this entry != mTop, Entry::line is used instead of g_Debugger.mCurrLine, // which means that it needs to point to the last executed line at that depth. The // following fixes a bug where the line number of this entry appears to revert to // the first line of the function or sub whenever the debugger steps into another // function or sub. Entry::line is now also used by BIF_Exception even when the // debugger is disconnected, which has two consequences: // - g_script.mCurrLine must be used in place of g_Debugger.mCurrLine. // - Changing PreExecLine() to update mStack.mTop->line won't help. mTop->line = g_script.mCurrLine; } return ++mTop; } void Debugger::PropertyWriter::WriteProperty(LPCSTR aName, ExprTokenType &aValue) { mDbg.AppendKeyName(mNameBuf, mNameLength, aName); // See BeginProperty() for comments about this line. _WriteProperty(aValue); } void Debugger::PropertyWriter::WriteProperty(INT_PTR aKey, ExprTokenType &aValue) { mNameBuf.AppendFormat("[%Ii]", aKey); _WriteProperty(aValue); } void Debugger::PropertyWriter::WriteProperty(IObject *aKey, ExprTokenType &aValue) { mNameBuf.AppendFormat("[Object(%Ii)]", aKey); _WriteProperty(aValue); } void Debugger::PropertyWriter::_WriteProperty(ExprTokenType &aValue) { if (mError) return; // Find the property's "relative" name at the end of the buffer: LPCSTR name = mNameBuf.GetString() + mNameLength; if (*name == '.') name++; // Write the property (and if it contains an object, any child properties): mError = mDbg.WritePropertyXml(aValue, name, mNameBuf, mPageSize, mMaxDepth - mDepth, mMaxEncodedSize); // Truncate back to the parent property name: mNameBuf.Truncate(mNameLength); } void Debugger::PropertyWriter::BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie) { if (mError) return; mDepth++; if (mDepth == 1) // Write <property> for the object itself. { LPCSTR classname = typeid(*mObject).name(); if (!strncmp(classname, "class ", 6)) classname += 6; mError = mDbg.mResponseBuf.WriteF("<property name=\"%e\" fullname=\"%e\" type=\"%s\" classname=\"%s\" address=\"%p\" size=\"0\" page=\"%i\" pagesize=\"%i\" children=\"%i\" numchildren=\"%i\">" , mName, mNameBuf.GetString(), aType, classname, mObject, mPage, mPageSize, aNumChildren > 0, aNumChildren); return; } // aName is the raw name of this property. Before writing it into the response, // convert it to the required expression-like form. Do this conversion within // mNameBuf so it can be used for the fullname attribute: mDbg.AppendKeyName(mNameBuf, mNameLength, aName); // Find the property's "relative" name at the end of the buffer: LPCSTR name = mNameBuf.GetString() + mNameLength; if (*name == '.') name++; // Save length of outer property name and update mNameLength. aCookie = (DebugCookie)mNameLength; mNameLength = mNameBuf.GetLength(); mError = mDbg.mResponseBuf.WriteF("<property name=\"%e\" fullname=\"%e\" type=\"%s\" size=\"0\" page=\"0\" pagesize=\"%i\" children=\"%i\" numchildren=\"%i\">" , name, mNameBuf.GetString(), aType, mPageSize, aNumChildren > 0, aNumChildren); } void Debugger::PropertyWriter::EndProperty(DebugCookie aCookie) { if (mError) return; mDepth--; if (mDepth > 0) // If we just ended a child property... { mNameLength = (size_t)aCookie; // Restore to the value it had before BeginProperty(). mNameBuf.Truncate(mNameLength); } mError = mDbg.mResponseBuf.Write("</property>"); } #endif // Helper for Var::ToText(). LPTSTR Var::ObjectToText(LPTSTR aBuf, int aBufSize) { LPTSTR aBuf_orig = aBuf; - aBuf += sntprintf(aBuf, aBufSize, _T("%s: Object(0x%p)"), mName, Object()); - if (ComObject *cobj = dynamic_cast<ComObject *>(Object())) + aBuf += sntprintf(aBuf, aBufSize, _T("%s: Object(0x%p)"), mName, mObject); + if (ComObject *cobj = dynamic_cast<ComObject *>(mObject)) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" <= ComObject(0x%04hX, 0x%I64X)"), cobj->mVarType, cobj->mVal64); return aBuf; } diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp index 31ce120..d859c03 100644 --- a/source/lowlevelbif.cpp +++ b/source/lowlevelbif.cpp @@ -1,129 +1,133 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" BIF_DECL(BIF_FindFunc) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } BIF_DECL(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00 { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname); aResultToken.value_int64 = (__int64)ahkFindLabel(labelname); return; } BIF_DECL(BIF_Getvar) { switch(aParam[0]->symbol) { case SYM_STRING: case SYM_OPERAND: if (!(TokenToInt64(*aParam[0]))) aResultToken.value_int64 = (__int64)g_script.FindOrAddVar(aParam[0]->marker); break; case SYM_VAR: aResultToken.value_int64 = (__int64)aParam[0]->var; break; default: aResultToken.value_int64 = 0; } } BIF_DECL(BIF_Alias) { ExprTokenType &aParam0 = *aParam[0]; ExprTokenType &aParam1 = *aParam[1]; aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (aParam0.symbol == SYM_VAR) { Var &var = *aParam0.var; UINT_PTR len = 0; if (aParamCount == 2) switch (aParam1.symbol) { case SYM_VAR: len = (UINT_PTR)(aParam[1]->var->mType == VAR_ALIAS ? aParam1.var->ResolveAlias() : aParam1.var); break; case SYM_INTEGER: // HotKeyIt added to accept var pointer len = (UINT_PTR)aParam[1]->value_int64; break; // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll case SYM_STRING: case SYM_OPERAND: len = (UINT_PTR)ATOI64(aParam1.marker); } var.mType = len ? VAR_ALIAS : VAR_NORMAL; var.mByteLength = len; + if (len && var.mAliasFor->HasObject()){ + var.mObject = var.mAliasFor->Object(); + var.mObject->AddRef(); + } } } BIF_DECL(BIF_CacheEnable) { if (aParam[0]->symbol == SYM_VAR) { (aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var) ->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; } } BIF_DECL(BIF_getTokenValue) { ExprTokenType *token = aParam[0]; if (token->symbol != SYM_INTEGER) return; token = (ExprTokenType*) token->value_int64; if (token->symbol == SYM_VAR) { Var &var = *token->var; VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE); if (cache_attrib) { aResultToken.symbol = (SymbolType) (cache_attrib >> 4); aResultToken.value_int64 = var.mContentsInt64; } else if (var.mAttrib & VAR_ATTRIB_OBJECT) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = var.mObject; } else { aResultToken.symbol = SYM_OPERAND; aResultToken.marker = var.mCharContents; } } else { aResultToken.symbol = token->symbol; aResultToken.value_int64 = token->value_int64; } if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->AddRef(); } \ No newline at end of file
tinku99/ahkdll
8e556ab31f8d778a91fc6be9d7d27556a9641fae
Fix Var::ObjectToText for Alias
diff --git a/source/Debugger.cpp b/source/Debugger.cpp index 75044c5..4ae69ca 100644 --- a/source/Debugger.cpp +++ b/source/Debugger.cpp @@ -2252,517 +2252,517 @@ int Debugger::Disconnect() // void Debugger::Exit(ExitReasons aExitReason, char *aCommandName) { if (mSocket == INVALID_SOCKET) return; // Don't care if it fails as we may be exiting due to a previous failure. SendContinuationResponse(aCommandName, "stopped", aExitReason == EXIT_ERROR ? "error" : "ok"); Disconnect(); } int Debugger::FatalError(LPCTSTR aMessage) { g_Debugger.Disconnect(); if (IDNO == MessageBox(g_hWnd, aMessage, g_script.mFileSpec, MB_YESNO | MB_ICONSTOP | MB_SETFOREGROUND | MB_APPLMODAL)) { // The following will exit even if the OnExit subroutine does not use ExitApp: g_script.ExitApp(EXIT_ERROR, _T("")); } return DEBUGGER_E_INTERNAL_ERROR; } const char *Debugger::sBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; #define BINARY_TO_BASE64_CHAR(b) (sBase64Chars[(b) & 63]) #define BASE64_CHAR_TO_BINARY(q) (strchr(sBase64Chars, q)-sBase64Chars) // Encode base 64 data. size_t Debugger::Base64Encode(char *aBuf, const char *aInput, size_t aInputSize/* = -1*/) { UINT_PTR buffer; size_t i, len = 0; if (aInputSize == -1) // Direct comparison since aInputSize is unsigned. aInputSize = strlen(aInput); for (i = aInputSize; i > 2; i -= 3) { buffer = (UCHAR)aInput[0] << 16 | (UCHAR)aInput[1] << 8 | (UCHAR)aInput[2]; // L39: Fixed for chars outside the range 0..127. [thanks jackieku] aInput += 3; aBuf[len + 0] = BINARY_TO_BASE64_CHAR(buffer >> 18); aBuf[len + 1] = BINARY_TO_BASE64_CHAR(buffer >> 12); aBuf[len + 2] = BINARY_TO_BASE64_CHAR(buffer >> 6); aBuf[len + 3] = BINARY_TO_BASE64_CHAR(buffer); len += 4; } if (i > 0) { buffer = (UCHAR)aInput[0] << 16; if (i > 1) buffer |= (UCHAR)aInput[1] << 8; // aInput not incremented as it is not used below. aBuf[len + 0] = BINARY_TO_BASE64_CHAR(buffer >> 18); aBuf[len + 1] = BINARY_TO_BASE64_CHAR(buffer >> 12); aBuf[len + 2] = (i > 1) ? BINARY_TO_BASE64_CHAR(buffer >> 6) : '='; aBuf[len + 3] = '='; len += 4; } aBuf[len] = '\0'; return len; } // Decode base 64 data. aBuf and aInput may point to the same buffer. size_t Debugger::Base64Decode(char *aBuf, const char *aInput, size_t aInputSize/* = -1*/) { UINT_PTR buffer; size_t i, len = 0; if (aInputSize == -1) // Direct comparison since aInputSize is unsigned. aInputSize = strlen(aInput); while (aInputSize > 0 && aInput[aInputSize-1] == '=') --aInputSize; for (i = aInputSize; i > 3; i -= 4) { buffer = BASE64_CHAR_TO_BINARY(aInput[0]) << 18 // L39: Fixed bad reliance on order of *side-effects++. [thanks fincs] | BASE64_CHAR_TO_BINARY(aInput[1]) << 12 | BASE64_CHAR_TO_BINARY(aInput[2]) << 6 | BASE64_CHAR_TO_BINARY(aInput[3]); aInput += 4; aBuf[len + 0] = (buffer >> 16) & 255; aBuf[len + 1] = (buffer >> 8) & 255; aBuf[len + 2] = buffer & 255; len += 3; } if (i > 1) { buffer = BASE64_CHAR_TO_BINARY(aInput[0]) << 18 | BASE64_CHAR_TO_BINARY(aInput[1]) << 12; if (i > 2) buffer |= BASE64_CHAR_TO_BINARY(aInput[2]) << 6; // aInput not incremented as it is not used below. aBuf[len++] = (buffer >> 16) & 255; if (i > 2) aBuf[len++] = (buffer >> 8) & 255; } aBuf[len] = '\0'; return len; } // // class Debugger::Buffer - simplifies memory management. // // Write data into the buffer, expanding it as necessary. int Debugger::Buffer::Write(char *aData, size_t aDataSize) { if (mFailed) // See WriteF() for comments. return DEBUGGER_E_INTERNAL_ERROR; if (aDataSize == -1) aDataSize = strlen(aData); if (aDataSize == 0) return DEBUGGER_E_OK; if (ExpandIfNecessary(mDataUsed + aDataSize) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; memcpy(mData + mDataUsed, aData, aDataSize); mDataUsed += aDataSize; return DEBUGGER_E_OK; } // Write formatted data into the buffer. Supports %s (char*), %e (char*, "&'<> escaped), %i (int), %u (unsigned int), %p (UINT_PTR). int Debugger::Buffer::WriteF(const char *aFormat, ...) { if (mFailed) { // A prior Write() failed and the now-invalid data hasn't yet been cleared // from the buffer. Abort. This allows numerous other parts of the code // to omit error-checking. return DEBUGGER_E_INTERNAL_ERROR; } int i; size_t len; char c; const char *format_ptr, *s, *param_ptr, *entity; char number_buf[MAX_INTEGER_SIZE]; va_list vl; for (len = 0, i = 0; i < 2; ++i) { va_start(vl, aFormat); // Calculate the required buffer size. for (format_ptr = aFormat; c = *format_ptr; ++format_ptr) { if (c == '%') { switch (format_ptr[1]) { case 's': s = va_arg(vl, char*); break; case 'i': s = _itoa(va_arg(vl, int), number_buf, 10); break; case 'u': s = _ultoa(va_arg(vl, unsigned long), number_buf, 10); break; case 'p': s = Exp32or64(_ultoa,_ui64toa)(va_arg(vl, UINT_PTR), number_buf, 10); break; case 'e': // String, replace "&'<> with appropriate XML entity. { s = va_arg(vl, char*); if (i == 0) { for (param_ptr = s; *param_ptr; ++param_ptr) { switch (*param_ptr) { case '"': case '\'': len += 6; break; // &quot; or &apos; case '&': len += 5; break; // &amp; case '<': case '>': len += 4; break; // &lt; or &gt; default: ++len; } } } else { for (param_ptr = s; c = *param_ptr; ++param_ptr) { switch (c) { case '"': entity = "quot"; break; case '\'': entity = "apos"; break; case '&': entity = "amp"; break; case '<': entity = "lt"; break; case '>': entity = "gt"; break; default: mData[mDataUsed++] = c; continue; } // One of: "'&<> - entity is set to the appropriate entity name. mDataUsed += sprintf(mData + mDataUsed, "&%s;", entity); } } ++format_ptr; // Skip %, outer loop will skip format char. //s = NULL; // Skip section below. //break; continue; } default: s = NULL; // Skip section below. } // switch (format_ptr[1]) if (s) { // %s, %i or %u. if (i == 0) { // Calculate required buffer space on first iteration. len += strlen(s); } else if (len = strlen(s)) { // Write into buffer on second iteration. // memcpy as we don't want the terminating null character. memcpy(mData + mDataUsed, s, len); mDataUsed += len; } ++format_ptr; // Skip %, outer loop will skip format char. continue; } } // if (c == '%') // Count or copy character as is. if (i == 0) ++len; else mData[mDataUsed++] = *format_ptr; } // for (format_ptr = aFormat; c = *format_ptr; ++format_ptr) if (i == 0) if (ExpandIfNecessary(mDataUsed + len) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; } // for (len = 0, i = 0; i < 2; ++i) return DEBUGGER_E_OK; } // Convert a file path to a URI and write it to the buffer. int Debugger::Buffer::WriteFileURI(const char *aPath) { int c, len = 9; // 8 for "file:///", 1 for '\0' (written by sprintf()). // Calculate required buffer size for path after encoding. for (const char *ptr = aPath; c = *ptr; ++ptr) { if (cisalnum(c) || strchr("-_.!~*'()/\\", c)) ++len; else len += 3; } // Ensure the buffer contains enough space. if (ExpandIfNecessary(mDataUsed + len) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; Write("file:///", 8); // Write to the buffer, encoding as we go. for (const char *ptr = aPath; c = *ptr; ++ptr) { if (cisalnum(c) || strchr("-_.!~*()/", c)) { mData[mDataUsed++] = (char)c; } else if (c == '\\') { // This could be encoded as %5C, but it's more readable this way: mData[mDataUsed++] = '/'; } else { len = sprintf(mData + mDataUsed, "%%%02X", c & 0xff); if (len != -1) mDataUsed += len; } } return DEBUGGER_E_OK; } int Debugger::Buffer::WriteEncodeBase64(const char *aInput, size_t aInputSize, bool aSkipBufferSizeCheck/* = false*/) { if (aInputSize) { if (!aSkipBufferSizeCheck) { // Ensure required buffer space is available. if (ExpandIfNecessary(mDataUsed + DEBUGGER_BASE64_ENCODED_SIZE(aInputSize)) != DEBUGGER_E_OK) return DEBUGGER_E_INTERNAL_ERROR; } //else caller has already ensured there is enough space and wants to be absolutely sure mData isn't reallocated. ASSERT(mDataUsed + aInputSize < mDataSize); if (aInput) mDataUsed += Debugger::Base64Encode(mData + mDataUsed, aInput, aInputSize); //else caller wanted to reserve some buffer space, probably to read the raw data into. } //else there's nothing to write, just return OK. Calculations above can't handle (size_t)0 return DEBUGGER_E_OK; } // Decode a file URI in-place. void Debugger::DecodeURI(char *aUri) { char *end = strchr(aUri, 0); char escape[3]; escape[2] = '\0'; if (!strnicmp(aUri, "file:///", 8)) { // Use memmove since I'm not sure if strcpy can handle overlap. end -= 8; memmove(aUri, aUri + 8, end - aUri); } // Some debugger UI's use file://path even though it is invalid (it should be file:///path or file://server/path). // For compatibility with these UI's, support file://. else if (!strnicmp(aUri, "file://", 7)) { end -= 7; memmove(aUri, aUri + 7, end - aUri); } char *dst, *src; for (src = dst = aUri; src < end; ++src, ++dst) { if (*src == '%' && src + 2 < end) { escape[0] = *++src; escape[1] = *++src; *dst = (char)strtol(escape, NULL, 16); } else if (*src == '/') *dst = '\\'; else *dst = *src; } *dst = '\0'; } // Initialize or expand the buffer, don't care how much. int Debugger::Buffer::Expand() { return ExpandIfNecessary(mDataSize ? mDataSize * 2 : DEBUGGER_INITIAL_BUFFER_SIZE); } // Expand as necessary to meet a minimum required size. int Debugger::Buffer::ExpandIfNecessary(size_t aRequiredSize) { if (mFailed) return DEBUGGER_E_INTERNAL_ERROR; size_t new_size; for (new_size = mDataSize ? mDataSize : DEBUGGER_INITIAL_BUFFER_SIZE ; new_size < aRequiredSize ; new_size *= 2); if (new_size > mDataSize) { // For simplicity, this preserves all of mData not just the first mDataUsed bytes. Some sections may rely on this. char *new_data = (char*)realloc(mData, new_size); if (new_data == NULL) { mFailed = TRUE; return DEBUGGER_E_INTERNAL_ERROR; } mData = new_data; mDataSize = new_size; } return DEBUGGER_E_OK; } // Remove data from the front of the buffer (i.e. after it is processed). void Debugger::Buffer::Remove(size_t aDataSize) { ASSERT(aDataSize <= mDataUsed); // Move remaining data to the front of the buffer. if (aDataSize < mDataUsed) memmove(mData, mData + aDataSize, mDataUsed - aDataSize); mDataUsed -= aDataSize; } void Debugger::Buffer::Clear() { mDataUsed = 0; mFailed = FALSE; } DbgStack::Entry *DbgStack::Push() { if (mTop == mTopBound) Expand(); if (mTop >= mBottom) { // Whenever this entry != mTop, Entry::line is used instead of g_Debugger.mCurrLine, // which means that it needs to point to the last executed line at that depth. The // following fixes a bug where the line number of this entry appears to revert to // the first line of the function or sub whenever the debugger steps into another // function or sub. Entry::line is now also used by BIF_Exception even when the // debugger is disconnected, which has two consequences: // - g_script.mCurrLine must be used in place of g_Debugger.mCurrLine. // - Changing PreExecLine() to update mStack.mTop->line won't help. mTop->line = g_script.mCurrLine; } return ++mTop; } void Debugger::PropertyWriter::WriteProperty(LPCSTR aName, ExprTokenType &aValue) { mDbg.AppendKeyName(mNameBuf, mNameLength, aName); // See BeginProperty() for comments about this line. _WriteProperty(aValue); } void Debugger::PropertyWriter::WriteProperty(INT_PTR aKey, ExprTokenType &aValue) { mNameBuf.AppendFormat("[%Ii]", aKey); _WriteProperty(aValue); } void Debugger::PropertyWriter::WriteProperty(IObject *aKey, ExprTokenType &aValue) { mNameBuf.AppendFormat("[Object(%Ii)]", aKey); _WriteProperty(aValue); } void Debugger::PropertyWriter::_WriteProperty(ExprTokenType &aValue) { if (mError) return; // Find the property's "relative" name at the end of the buffer: LPCSTR name = mNameBuf.GetString() + mNameLength; if (*name == '.') name++; // Write the property (and if it contains an object, any child properties): mError = mDbg.WritePropertyXml(aValue, name, mNameBuf, mPageSize, mMaxDepth - mDepth, mMaxEncodedSize); // Truncate back to the parent property name: mNameBuf.Truncate(mNameLength); } void Debugger::PropertyWriter::BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie) { if (mError) return; mDepth++; if (mDepth == 1) // Write <property> for the object itself. { LPCSTR classname = typeid(*mObject).name(); if (!strncmp(classname, "class ", 6)) classname += 6; mError = mDbg.mResponseBuf.WriteF("<property name=\"%e\" fullname=\"%e\" type=\"%s\" classname=\"%s\" address=\"%p\" size=\"0\" page=\"%i\" pagesize=\"%i\" children=\"%i\" numchildren=\"%i\">" , mName, mNameBuf.GetString(), aType, classname, mObject, mPage, mPageSize, aNumChildren > 0, aNumChildren); return; } // aName is the raw name of this property. Before writing it into the response, // convert it to the required expression-like form. Do this conversion within // mNameBuf so it can be used for the fullname attribute: mDbg.AppendKeyName(mNameBuf, mNameLength, aName); // Find the property's "relative" name at the end of the buffer: LPCSTR name = mNameBuf.GetString() + mNameLength; if (*name == '.') name++; // Save length of outer property name and update mNameLength. aCookie = (DebugCookie)mNameLength; mNameLength = mNameBuf.GetLength(); mError = mDbg.mResponseBuf.WriteF("<property name=\"%e\" fullname=\"%e\" type=\"%s\" size=\"0\" page=\"0\" pagesize=\"%i\" children=\"%i\" numchildren=\"%i\">" , name, mNameBuf.GetString(), aType, mPageSize, aNumChildren > 0, aNumChildren); } void Debugger::PropertyWriter::EndProperty(DebugCookie aCookie) { if (mError) return; mDepth--; if (mDepth > 0) // If we just ended a child property... { mNameLength = (size_t)aCookie; // Restore to the value it had before BeginProperty(). mNameBuf.Truncate(mNameLength); } mError = mDbg.mResponseBuf.Write("</property>"); } #endif // Helper for Var::ToText(). LPTSTR Var::ObjectToText(LPTSTR aBuf, int aBufSize) { LPTSTR aBuf_orig = aBuf; - aBuf += sntprintf(aBuf, aBufSize, _T("%s[Object]: 0x%p"), mName, mObject); - if (ComObject *cobj = dynamic_cast<ComObject *>(mObject)) + aBuf += sntprintf(aBuf, aBufSize, _T("%s: Object(0x%p)"), mName, Object()); + if (ComObject *cobj = dynamic_cast<ComObject *>(Object())) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" <= ComObject(0x%04hX, 0x%I64X)"), cobj->mVarType, cobj->mVal64); return aBuf; } diff --git a/source/script.cpp b/source/script.cpp index 190f984..c6512f7 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -18182,1025 +18182,1025 @@ LPTSTR Line::LogToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int t #ifndef AUTOHOTKEYSC int last_file_index = -1; #endif DWORD elapsed; bool this_item_is_special, next_item_is_special; // In the below, sLogNext causes it to start at the oldest logged line and continue up through the newest: for (lines_to_show = LINE_LOG_SIZE, line_index = sLogNext;;) // Retry with fewer lines in case the first attempt doesn't fit in the buffer. { aBuf = aBuf_log_start; // Reset target position in buffer to the place where log should begin. for (next_item_is_special = false, i = 0; i < lines_to_show; ++i, ++line_index) { if (line_index >= LINE_LOG_SIZE) // wrap around, because sLog is a circular queue line_index -= LINE_LOG_SIZE; // Don't just reset it to zero because an offset larger than one may have been added to it. if (!sLog[line_index]) // No line has yet been logged in this slot. continue; // ACT_LISTLINES and other things might rely on "continue" isntead of halting the loop here. this_item_is_special = next_item_is_special; next_item_is_special = false; // Set default. if (i + 1 < lines_to_show) // There are still more lines to be processed { if (this_item_is_special) // And we know from the above that this special line is not the last line. // Due to the fact that these special lines are usually only useful when they appear at the // very end of the log, omit them from the log-display when they're not the last line. // In the case of a high-frequency SetTimer, this greatly reduces the log clutter that // would otherwise occur: continue; // Since above didn't continue, this item isn't special, so display it normally. elapsed = sLogTick[line_index + 1 >= LINE_LOG_SIZE ? 0 : line_index + 1] - sLogTick[line_index]; if (elapsed > INT_MAX) // INT_MAX is about one-half of DWORD's capacity. { // v1.0.30.02: Assume that huge values (greater than 24 days or so) were caused by // the new policy of storing WinWait/RunWait/etc.'s line in the buffer whenever // it was interrupted and later resumed by a thread. In other words, there are now // extra lines in the buffer which are considered "special" because they don't indicate // a line that actually executed, but rather one that is still executing (waiting). // See ACT_WINWAIT for details. next_item_is_special = true; // Override the default. if (i + 2 == lines_to_show) // The line after this one is not only special, but the last one that will be shown, so recalculate this one correctly. elapsed = GetTickCount() - sLogTick[line_index]; else // Neither this line nor the special one that follows it is the last. { // Refer to the line after the next (special) line to get this line's correct elapsed time. line_index2 = line_index + 2; if (line_index2 >= LINE_LOG_SIZE) line_index2 -= LINE_LOG_SIZE; elapsed = sLogTick[line_index2] - sLogTick[line_index]; } } } else // This is the last line (whether special or not), so compare it's time against the current time instead. elapsed = GetTickCount() - sLogTick[line_index]; #ifndef AUTOHOTKEYSC // If the this line and the previous line are in different files, display the filename: if (last_file_index != sLog[line_index]->mFileIndex) { last_file_index = sLog[line_index]->mFileIndex; aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("---- %s\r\n"), sSourceFile[last_file_index]); } #endif space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate really huge lines so that the Edit control's size is less likely to be exhausted. // In v1.0.30.02, this is even more likely due to having increased the line-buf's capacity from // 200 to 400, therefore the truncation point was reduced from 500 to 200 to make it more likely // that the first attempt to fit the lines_to_show number of lines into the buffer will succeed. aBuf = sLog[line_index]->ToText(aBuf, space_remaining < 200 ? space_remaining : 200, true, elapsed, this_item_is_special); // If the line above can't fit everything it needs into the remaining space, it will fill all // of the remaining space, and thus the check against LINE_LOG_FINAL_MESSAGE_LENGTH below // should never fail to catch that, and then do a retry. } // Inner for() #define LINE_LOG_FINAL_MESSAGE _T("\r\nPress [F5] to refresh.") // Keep the next line in sync with this. #define LINE_LOG_FINAL_MESSAGE_LENGTH 24 if (BUF_SPACE_REMAINING > LINE_LOG_FINAL_MESSAGE_LENGTH || lines_to_show < 120) // Either success or can't succeed. break; // Otherwise, there is insufficient room to put everything in, but there's still room to retry // with a smaller value of lines_to_show: lines_to_show -= 100; line_index = sLogNext + (LINE_LOG_SIZE - lines_to_show); // Move the starting point forward in time so that the oldest log entries are omitted. } // outer for() that retries the log-to-buffer routine. // Must add the return value, not LINE_LOG_FINAL_MESSAGE_LENGTH, in case insufficient room (i.e. in case // outer loop terminated due to lines_to_show being too small). return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, LINE_LOG_FINAL_MESSAGE); } LPTSTR Line::VicinityToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 the current line and the lines above and below it into their text equivalent // putting the result into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; #define LINES_ABOVE_AND_BELOW 7 // Determine the correct value for line_start and line_end: int i; Line *line_start, *line_end; for (i = 0, line_start = this ; i < LINES_ABOVE_AND_BELOW && line_start->mPrevLine != NULL ; ++i, line_start = line_start->mPrevLine); for (i = 0, line_end = this ; i < LINES_ABOVE_AND_BELOW && line_end->mNextLine != NULL ; ++i, line_end = line_end->mNextLine); #ifdef AUTOHOTKEYSC if (!g_AllowMainWindow) // Override the above to show only a single line, to conceal the script's source code. { line_start = this; line_end = this; } #endif // Now line_start and line_end are the first and last lines of the range // we want to convert to text, and they're non-NULL. aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\tLine#\n")); int space_remaining; // Must be an int to preserve any negative results. // Start at the oldest and continue up through the newest: for (Line *line = line_start;;) { if (line == this) tcslcpy(aBuf, _T("--->\t"), BUF_SPACE_REMAINING); else tcslcpy(aBuf, _T("\t"), BUF_SPACE_REMAINING); aBuf += _tcslen(aBuf); space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate large lines so that the dialog is more readable: aBuf = line->ToText(aBuf, space_remaining < 500 ? space_remaining : 500, false); if (line == line_end) break; line = line->mNextLine; } return aBuf; } LPTSTR Line::ToText(LPTSTR aBuf, int aBufSize, bool aCRLF, DWORD aElapsed, bool aLineWasResumed) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 line into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. { if (aBufSize < 3) return aBuf; else aBufSize -= (1 + aCRLF); // Reserve one char for LF/CRLF after each line (so that it always get added). LPTSTR aBuf_orig = aBuf; aBuf += sntprintf(aBuf, aBufSize, _T("%03u: "), mLineNumber); if (aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("STILL WAITING (%0.2f): "), (float)aElapsed / 1000.0); if (mActionType == ACT_IFBETWEEN || mActionType == ACT_IFNOTBETWEEN) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("if %s %s %s and %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2, RAW_ARG3); else if (ACT_IS_ASSIGN(mActionType) || (ACT_IS_IF(mActionType) && mActionType < ACT_FIRST_COMMAND)) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s%s %s %s") , ACT_IS_IF(mActionType) ? _T("if ") : _T("") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2); else if (mActionType == ACT_FOR) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("For %s,%s in %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , *mArg[1].text || !VAR(mArg[1]) ? mArg[1].text : VAR(mArg[1])->mName // can be omitted. , mArg[2].text); else { aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s"), g_act[mActionType].Name); for (int i = 0; i < mArgc; ++i) // This method a little more efficient than using snprintfcat(). // Also, always use the arg's text for input and output args whose variables haven't // been resolved at load-time, since the text has everything in it we want to display // and thus there's no need to "resolve" dynamic variables here (e.g. array%i%). aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(",%s"), (mArg[i].type != ARG_TYPE_NORMAL && !*mArg[i].text) ? VAR(mArg[i])->mName : mArg[i].text); } if (aElapsed && !aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" (%0.2f)"), (float)aElapsed / 1000.0); // UPDATE for v1.0.25: It seems that MessageBox(), which is the only way these lines are currently // displayed, prefers \n over \r\n because otherwise, Ctrl-C on the MsgBox copies the lines all // onto one line rather than formatted nicely as separate lines. // Room for LF or CRLF was reserved at the top of this function: if (aCRLF) *aBuf++ = '\r'; *aBuf++ = '\n'; *aBuf = '\0'; return aBuf; } #ifndef MINIDLL void Line::ToggleSuspendState() { // If suspension is being turned on: // It seems unnecessary, and possibly undesirable, to purge any pending hotkey msgs from the msg queue. // Even if there are some, it's possible that they are exempt from suspension so we wouldn't want to // globally purge all messages anyway. g_IsSuspended = !g_IsSuspended; Hotstring::SuspendAll(g_IsSuspended); // Must do this prior to ManifestAllHotkeysHotstringsHooks() to avoid incorrect removal of hook. Hotkey::ManifestAllHotkeysHotstringsHooks(); // Update the state of all hotkeys based on the complex interdependencies hotkeys have with each another. g_script.UpdateTrayIcon(); CheckMenuItem(GetMenu(g_hWnd), ID_FILE_SUSPEND, g_IsSuspended ? MF_CHECKED : MF_UNCHECKED); } #endif void Line::PauseUnderlyingThread(bool aTrueForPauseFalseForUnpause) { if (g <= g_array) // Guard against underflow. This condition can occur when the script thread that called us is the AutoExec section or a callback running in the idle/0 thread. return; if (g[-1].IsPaused == aTrueForPauseFalseForUnpause) // It's already in the right state. return; // Return early because doing the updates further below would be wrong in this case. g[-1].IsPaused = aTrueForPauseFalseForUnpause; // Update the pause state to that specified by caller. if (aTrueForPauseFalseForUnpause) // The underlying thread is being paused when it was unpaused before. ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. else // The underlying thread is being unpaused when it was paused before. --g_nPausedThreads; } ResultType Line::ChangePauseState(ToggleValueType aChangeTo, bool aAlwaysOperateOnUnderlyingThread) // Currently designed to be called only by the Pause command (ACT_PAUSE). // Returns OK or FAIL. { switch (aChangeTo) { case TOGGLED_ON: break; // By breaking instead of returning, pause will be put into effect further below. case TOGGLED_OFF: // v1.0.37.06: The old method was to unpause the the nearest paused thread on the call stack; // but it was flawed because if the thread that made the flag true is interrupted, and the new // thread is paused via the pause command, and that thread is then interrupted, when the paused // thread resumes it would automatically and wrongly be unpaused (i.e. the unpause ticket would // be used at a level higher in the call stack than intended). // Flag this thread so that when it ends, the thread beneath it will be unpaused. If that thread // (which can be the idle thread) isn't paused the following flag-change will be ignored at a later // stage. This method also relies on the fact that the current thread cannot itself be paused right // now because it is what got us here. PauseUnderlyingThread(false); // Necessary even for the "idle thread" (otherwise, the Pause command wouldn't be able to unpause it). return OK; case NEUTRAL: // the user omitted the parameter entirely, which is considered the same as "toggle" case TOGGLE: // Update for v1.0.37.06: "Pause" and "Pause Toggle" are more useful if they always apply to the // thread immediately beneath the current thread rather than "any underlying thread that's paused". if (g > g_array && g[-1].IsPaused) // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is called by the AutoExec section or a threadless callback running in thread #0. { PauseUnderlyingThread(false); return OK; } //ELSE since the underlying thread is not paused, continue onward to do the "pause enabled" logic below. // (This is the historical behavior because it allows a hotkey like F1::Pause to toggle the script's // pause state on and off -- even though what's really happening involves multiple threads.) break; default: // TOGGLE_INVALID or some other disallowed value. // We know it's a variable because otherwise the loading validation would have caught it earlier: return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); } // Since above didn't return, pause should be turned on. if (aAlwaysOperateOnUnderlyingThread) // v1.0.37.06: Allow underlying thread to be directly paused rather than pausing the current thread. { PauseUnderlyingThread(true); // If the underlying thread is already paused, this flag change will be ignored at a later stage. return OK; } // Otherwise, pause the current subroutine (which by definition isn't paused since it had to be // active to call us). It seems best not to attempt to change the Hotkey mRunAgainAfterFinished // attribute for the current hotkey (assuming it's even a hotkey that got us here) or // for them all. This is because it's conceivable that this Pause command occurred // in a background thread, such as a timed subroutine, in which case we wouldn't want the // pausing of that thread to affect anything else the user might be doing with hotkeys. // UPDATE: The above is flawed because by definition the script's quasi-thread that got // us here is now active. Since it is active, the script will immediately become dormant // when this is executed, waiting for the user to press a hotkey to launch a new // quasi-thread. Thus, it seems best to reset all the mRunAgainAfterFinished flags // in case we are in a hotkey subroutine and in case this hotkey has a buffered repeat-again // action pending, which the user probably wouldn't want to happen after the script is unpaused: #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif return OK; } ResultType Line::ScriptBlockInput(bool aEnable) // Always returns OK for caller convenience. { // Must be running Win98/2000+ for this function to be successful. // We must dynamically load the function to retain compatibility with Win95 (program won't launch // at all otherwise). typedef void (CALLBACK *BlockInput)(BOOL); static BlockInput lpfnDLLProc = (BlockInput)GetProcAddress(GetModuleHandle(_T("user32")), "BlockInput"); // Always turn input ON/OFF even if g_BlockInput says its already in the right state. This is because // BlockInput can be externally and undetectably disabled, e.g. if the user presses Ctrl-Alt-Del: if (lpfnDLLProc) (*lpfnDLLProc)(aEnable ? TRUE : FALSE); g_BlockInput = aEnable; return OK; // By design, it never returns FAIL. } Line *Line::PreparseError(LPTSTR aErrorText, LPTSTR aExtraInfo) // Returns a different type of result for use with the Pre-parsing methods. { // Make all preparsing errors critical because the runtime reliability // of the program relies upon the fact that the aren't any kind of // problems in the script (otherwise, unexpected behavior may result). // Update: It's okay to return FAIL in this case. CRITICAL_ERROR should // be avoided whenever OK and FAIL are sufficient by themselves, because // otherwise, callers can't use the NOT operator to detect if a function // failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero): LineError(aErrorText, FAIL, aExtraInfo); return NULL; // Always return NULL because the callers use it as their return value. } IObject *Line::CreateRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { // Build the parameters for Object::Create() ExprTokenType aParams[5*2]; int aParamCount = 4*2; ExprTokenType* aParam[5*2] = { aParams + 0, aParams + 1, aParams + 2, aParams + 3, aParams + 4 , aParams + 5, aParams + 6, aParams + 7, aParams + 8, aParams + 9 }; aParams[0].symbol = SYM_STRING; aParams[0].marker = _T("What"); aParams[1].symbol = SYM_STRING; aParams[1].marker = aWhat ? (LPTSTR)aWhat : g_act[mActionType].Name; aParams[2].symbol = SYM_STRING; aParams[2].marker = _T("File"); aParams[3].symbol = SYM_STRING; aParams[3].marker = Line::sSourceFile[mFileIndex]; aParams[4].symbol = SYM_STRING; aParams[4].marker = _T("Line"); aParams[5].symbol = SYM_INTEGER; aParams[5].value_int64 = mLineNumber; aParams[6].symbol = SYM_STRING; aParams[6].marker = _T("Message"); aParams[7].symbol = SYM_STRING; aParams[7].marker = (LPTSTR)aErrorText; if (aExtraInfo && *aExtraInfo) { aParamCount += 2; aParams[8].symbol = SYM_STRING; aParams[8].marker = _T("Extra"); aParams[9].symbol = SYM_STRING; aParams[9].marker = (LPTSTR)aExtraInfo; } return Object::Create(aParam, aParamCount); } ResultType Line::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { // ThrownToken may already exist if Assign() fails in ACT_CATCH, or possibly // in other extreme cases. In such a case, just free the old token. If this // line is CATCH, it won't handle the new exception; an outer TRY/CATCH will. if (g->ThrownToken) g_script.FreeExceptionToken(g->ThrownToken); ExprTokenType *token; if ( !(token = new ExprTokenType) || !(token->object = CreateRuntimeException(aErrorText, aWhat, aExtraInfo)) ) { // Out of memory. It's likely that we were called for this very reason. // Since we don't even have enough memory to allocate an exception object, // just show an error message and exit the thread. Don't call LineError(), // since that would recurse into this function. if (token) delete token; MsgBox(ERR_OUTOFMEM ERR_ABORT); return FAIL; } token->symbol = SYM_OBJECT; token->mem_to_free = NULL; g->ThrownToken = token; g->ExcptLine = this; // Returning FAIL causes each caller to also return FAIL, until either the // thread has fully exited or the recursion layer handling ACT_TRY is reached: return FAIL; } ResultType Script::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { return g_script.mCurrLine->ThrowRuntimeException(aErrorText, aWhat, aExtraInfo); } ResultType Line::SetErrorLevelOrThrowBool(bool aError) { if (!aError) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (!g->InTryBlock) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(ERRORLEVEL_ERROR); } ResultType Line::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue) { if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(aErrorValue); } ResultType Line::SetErrorLevelOrThrowInt(int aErrorValue) { if (!aErrorValue || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); TCHAR buf[12]; // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(_itot(aErrorValue, buf, 10)); } // Logic from the above functions is duplicated in the below functions rather than calling // g_script.mCurrLine->SetErrorLevelOrThrow() to squeeze out a little extra performance for // "success" cases. These are done as overloads vs making aMessage optional to reduce code // size, since they're called from numerous places. (Even omitted parameters are passed // "explicitly" in the compiled code.) ResultType Script::SetErrorLevelOrThrowBool(bool aError) { if (!aError) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (!g->InTryBlock) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(ERRORLEVEL_ERROR); } ResultType Script::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat) { if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(aErrorValue, aWhat); } ResultType Script::SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat) { if (!aErrorValue || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); TCHAR buf[12]; // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(_itot(aErrorValue, buf, 10), aWhat); } ResultType Line::SetErrorsOrThrow(bool aError, DWORD aLastErrorOverride) { // LastError is set even if we're going to throw an exception, for simplicity: g->LastError = aLastErrorOverride == -1 ? GetLastError() : aLastErrorOverride; return SetErrorLevelOrThrowBool(aError); } #define ERR_PRINT(fmt, ...) _ftprintf(stderr, fmt, __VA_ARGS__) ResultType Line::LineError(LPCTSTR aErrorText, ResultType aErrorType, LPCTSTR aExtraInfo) { if (!aErrorText) aErrorText = _T(""); if (!aExtraInfo) aExtraInfo = _T(""); if (g->InTryBlock && (aErrorType == FAIL || aErrorType == EARLY_EXIT)) // FAIL is most common, but EARLY_EXIT is used by ComError(). WARN and CRITICAL_ERROR are excluded. return ThrowRuntimeException(aErrorText, NULL, aExtraInfo); if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute && aErrorType != WARN) // i.e. runtime errors are always displayed via dialog. { // JdeB said: // Just tested it in Textpad, Crimson and Scite. they all recognise the output and jump // to the Line containing the error when you double click the error line in the output // window (like it works in C++). Had to change the format of the line to: // printf("%s (%d) : ==> %s: \n%s \n%s\n",szInclude, nAutScriptLine, szText, szScriptLine, szOutput2 ); // MY: Full filename is required, even if it's the main file, because some editors (EditPlus) // seem to rely on that to determine which file and line number to jump to when the user double-clicks // the error message in the output window. // v1.0.47: Added a space before the colon as originally intended. Toralf said, "With this minor // change the error lexer of Scite recognizes this line as a Microsoft error message and it can be // used to jump to that line." #define STD_ERROR_FORMAT _T("%s (%d) : ==> %s\n") ERR_PRINT(STD_ERROR_FORMAT, sSourceFile[mFileIndex], mLineNumber, aErrorText); // printf() does not significantly increase the size of the EXE, probably because it shares most of the same code with sprintf(), etc. if (*aExtraInfo) ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo); } else { TCHAR buf[MSGBOX_TEXT_SIZE]; FormatError(buf, _countof(buf), aErrorType, aErrorText, aExtraInfo, this // The last parameter determines the final line of the message: , (aErrorType == FAIL && g_script.mIsReadyToExecute) ? ERR_ABORT_NO_SPACES : (aErrorType == CRITICAL_ERROR || aErrorType == FAIL) ? (g_script.mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT) : (aErrorType == EARLY_EXIT) ? _T("Continue running the script?") : _T("For more details, read the documentation for #Warn.")); g_script.mCurrLine = this; // This needs to be set in some cases where the caller didn't. #ifdef CONFIG_DEBUGGER if (g_Debugger.HasStdErrHook()) g_Debugger.OutputDebug(buf); else #endif - if (MsgBox(buf, aErrorType == EARLY_EXIT ? MB_YESNO : 0) == IDNO) + if (MsgBox(buf, MB_TOPMOST | (aErrorType == EARLY_EXIT ? MB_YESNO : 0)) == IDNO) aErrorType = CRITICAL_ERROR; } if (aErrorType == CRITICAL_ERROR && g_script.mIsReadyToExecute) // Also ask the main message loop function to quit and announce to the system that // we expect it to quit. In most cases, this is unnecessary because all functions // called to get to this point will take note of the CRITICAL_ERROR and thus keep // return immediately, all the way back to main. However, there may cases // when this isn't true: // Note: Must do this only after MsgBox, since it appears that new dialogs can't // be created once it's done. Update: Using ExitApp() now, since it's known to be // more reliable: //PostQuitMessage(CRITICAL_ERROR); // This will attempt to run the OnExit subroutine, which should be okay since that subroutine // will terminate the script if it encounters another runtime error: g_script.ExitApp(EXIT_ERROR); return aErrorType; // The caller told us whether it should be a critical error or not. } int Line::FormatError(LPTSTR aBuf, int aBufSize, ResultType aErrorType, LPCTSTR aErrorText, LPCTSTR aExtraInfo, Line *aLine, LPCTSTR aFooter) { TCHAR source_file[MAX_PATH * 2]; if (aLine && aLine->mFileIndex) sntprintf(source_file, _countof(source_file), _T(" in #include file \"%s\""), sSourceFile[aLine->mFileIndex]); else *source_file = '\0'; // Don't bother cluttering the display if it's the main script file. LPTSTR aBuf_orig = aBuf; // Error message: aBuf += sntprintf(aBuf, aBufSize, _T("%s%s:%s %-1.500s\n\n") // Keep it to a sane size in case it's huge. , aErrorType == WARN ? _T("Warning") : (aErrorType == CRITICAL_ERROR ? _T("Critical Error") : _T("Error")) , source_file, *source_file ? _T("\n ") : _T(" "), aErrorText); // Specifically: if (*aExtraInfo) // Use format specifier to make sure really huge strings that get passed our // way, such as a var containing clipboard text, are kept to a reasonable size: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Specifically: %-1.100s%s\n\n") , aExtraInfo, _tcslen(aExtraInfo) > 100 ? _T("...") : _T("")); // Relevant lines of code: if (aLine) aBuf = aLine->VicinityToText(aBuf, BUF_SPACE_REMAINING); // What now?: if (aFooter) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\n%s"), aFooter); return (int)(aBuf - aBuf_orig); } ResultType Script::ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo) //, ResultType aErrorType) // Even though this is a Script method, including it here since it shares // a common theme with the other error-displaying functions: { if (mCurrLine) // If a line is available, do LineError instead since it's more specific. // If an error occurs before the script is ready to run, assume it's always critical // in the sense that the program will exit rather than run the script. // Update: It's okay to return FAIL in this case. CRITICAL_ERROR should // be avoided whenever OK and FAIL are sufficient by themselves, because // otherwise, callers can't use the NOT operator to detect if a function // failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero): return mCurrLine->LineError(aErrorText, FAIL, aExtraInfo); // Otherwise: The fact that mCurrLine is NULL means that the line currently being loaded // has not yet been successfully added to the linked list. Such errors will always result // in the program exiting. if (!aErrorText) aErrorText = _T("Unk"); // Placeholder since it shouldn't be NULL. if (!aExtraInfo) // In case the caller explicitly called it with NULL. aExtraInfo = _T(""); if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute) // i.e. runtime errors are always displayed via dialog. { // See LineError() for details. ERR_PRINT(STD_ERROR_FORMAT, Line::sSourceFile[mCurrFileIndex], mCombinedLineNumber, aErrorText); if (*aExtraInfo) ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo); } else { TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); cp += sntprintf(cp, buf_space_remaining, _T("Error at line %u"), mCombinedLineNumber); // Don't call it "critical" because it's usually a syntax error. buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (mCurrFileIndex) { cp += sntprintf(cp, buf_space_remaining, _T(" in #include file \"%s\""), Line::sSourceFile[mCurrFileIndex]); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } //else don't bother cluttering the display if it's the main script file. cp += sntprintf(cp, buf_space_remaining, _T(".\n\n")); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (*aExtraInfo) { cp += sntprintf(cp, buf_space_remaining, _T("Line Text: %-1.100s%s\nError: ") // i.e. the word "Error" is omitted as being too noisy when there's no ExtraInfo to put into the dialog. , aExtraInfo // aExtraInfo defaults to "" so this is safe. , _tcslen(aExtraInfo) > 100 ? _T("...") : _T("")); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } sntprintf(cp, buf_space_remaining, _T("%s\n\n%s"), aErrorText, mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT); //ShowInEditor(); #ifdef CONFIG_DEBUGGER if (g_Debugger.HasStdErrHook()) g_Debugger.OutputDebug(buf); else #endif MsgBox(buf); } return FAIL; // See above for why it's better to return FAIL than CRITICAL_ERROR. } ResultType Script::UnhandledException(ExprTokenType*& aToken, Line* aLine) { LPCTSTR message = _T(""), extra = _T(""); TCHAR extra_buf[MAX_NUMBER_SIZE], message_buf[MAX_NUMBER_SIZE]; if (Object *ex = dynamic_cast<Object *>(TokenToObject(*aToken))) { // For simplicity and safety, we call into the Object directly rather than via Invoke(). ExprTokenType t; if (ex->GetItem(t, _T("Message"))) message = TokenToString(t, message_buf); if (ex->GetItem(t, _T("Extra"))) extra = TokenToString(t, extra_buf); if (ex->GetItem(t, _T("Line"))) { LineNumberType line_no = (LineNumberType)TokenToInt64(t); if (ex->GetItem(t, _T("File"))) { LPCTSTR file = TokenToString(t); // Locate the line by number and file index, then display that line instead // of the caller supplied one since it's probably more relevant. int file_index; for (file_index = 0; file_index < Line::sSourceFileCount; ++file_index) if (!_tcsicmp(file, Line::sSourceFile[file_index])) break; Line *line; for (line = g_script.mFirstLine; line && (line->mLineNumber != line_no || line->mFileIndex != file_index); line = line->mNextLine); if (line) aLine = line; } } } else { // Assume it's a string or number. message = TokenToString(*aToken, message_buf); } // If message is empty or numeric, display a default message for clarity. if (!*extra && IsPureNumeric(message, TRUE, TRUE, TRUE)) { extra = message; message = _T("Unhandled exception."); } TCHAR buf[MSGBOX_TEXT_SIZE]; Line::FormatError(buf, _countof(buf), FAIL, message, extra, aLine, _T("The thread has exited.")); MsgBox(buf); FreeExceptionToken(aToken); return FAIL; } void Script::FreeExceptionToken(ExprTokenType*& aToken) { // If an object was thrown, release it. if (aToken->symbol == SYM_OBJECT) aToken->object->Release(); // If a string was thrown and memory allocated for it, free it. if (aToken->mem_to_free) free(aToken->mem_to_free); // Free the token itself. delete aToken; // Clear caller's variable. aToken = NULL; } void Script::ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo, Line *line) { if (warnMode == WARNMODE_OFF) return; if (!line) line = mCurrLine; int fileIndex = line ? line->mFileIndex : mCurrFileIndex; FileIndexType lineNumber = line ? line->mLineNumber : mCombinedLineNumber; TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); #define STD_WARNING_FORMAT _T("%s (%d) : ==> Warning: %s\n") cp += sntprintf(cp, buf_space_remaining, STD_WARNING_FORMAT, Line::sSourceFile[fileIndex], lineNumber, aWarningText); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (*aExtraInfo) { cp += sntprintf(cp, buf_space_remaining, _T(" Specifically: %s\n"), aExtraInfo); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } if (warnMode == WARNMODE_STDOUT) #ifndef CONFIG_DEBUGGER _fputts(buf, stdout); else OutputDebugString(buf); #else g_Debugger.FileAppendStdOut(buf); else g_Debugger.OutputDebug(buf); #endif // In MsgBox mode, MsgBox is in addition to OutputDebug if (warnMode == WARNMODE_MSGBOX) { if (!line) line = mCurrLine; // Call mCurrLine->LineError() vs ScriptError() to pass WARN. if (line) line->LineError(aWarningText, WARN, aExtraInfo); else // Realistically shouldn't happen. If it does, the message might be slightly // misleading since ScriptError isn't equipped to display "warning" messages. ScriptError(aWarningText, aExtraInfo); } } void Script::WarnUninitializedVar(Var *var) { bool isGlobal = !var->IsLocal(); WarnMode warnMode = isGlobal ? g_Warn_UseUnsetGlobal : g_Warn_UseUnsetLocal; if (!warnMode) return; // Note: If warning mode is MsgBox, this method has side effect of marking the var initialized, so that // only a single message box gets raised per variable. (In other modes, e.g. OutputDebug, the var remains // uninitialized because it may be beneficial to see the quantity and various locations of uninitialized // uses, and doesn't present the same user interface problem that multiple message boxes can.) if (warnMode == WARNMODE_MSGBOX) var->MarkInitialized(); bool isNonStaticLocal = var->IsNonStaticLocal(); LPCTSTR varClass = isNonStaticLocal ? _T("local") : (isGlobal ? _T("global") : _T("static")); LPCTSTR sameNameAsGlobal = (isNonStaticLocal && FindVar(var->mName, 0, NULL, FINDVAR_GLOBAL)) ? _T(" with same name as a global") : _T(""); TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); sntprintf(cp, buf_space_remaining, _T("%s (a %s variable%s)"), var->mName, varClass, sameNameAsGlobal); ScriptWarning(warnMode, WARNING_USE_UNSET_VARIABLE, buf); } void Script::MaybeWarnLocalSameAsGlobal(Func &func, Var &var) // Caller has verified the following: // 1) var is not a declared variable. // 2) a global variable with the same name definitely exists. { if (!g_Warn_LocalSameAsGlobal) return; #ifdef ENABLE_DLLCALL if (IsDllArgTypeName(var.mName)) // Exclude unquoted DllCall arg type names. Although variable names like "str" and "ptr" // might be used for other purposes, it seems far more likely that both this var and its // global counterpart (if it exists) are blank vars which were used as DllCall arg types. return; #endif Line *line = func.mJumpToLine; while (line && line->mActionType != ACT_BLOCK_BEGIN) line = line->mPrevLine; if (!line) line = func.mJumpToLine; TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); sntprintf(cp, buf_space_remaining, _T("%s (in function %s)"), var.mName, func.mName); ScriptWarning(g_Warn_LocalSameAsGlobal, WARNING_LOCAL_SAME_AS_GLOBAL, buf, line); } void Script::PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount) { for (int v = 0; v < aVarCount; ++v) { Var &var = *aVarList[v]; if (var.IsDeclared()) // Not a canditate for a super-global or warning. continue; Var *global_var = FindVar(var.mName, 0, NULL, FINDVAR_GLOBAL); if (!global_var) // No global variable with that name. continue; if (global_var->IsSuperGlobal()) { // Make this local variable an alias for the super-global. Above has already // verified this var was not declared and therefore isn't a function parameter. var.UpdateAlias(global_var); // Remove the variable from the local list to prevent it from being shown in // ListVars or being reset when the function returns. memmove(aVarList + v, aVarList + v + 1, (--aVarCount - v) * sizeof(Var *)); --v; // Counter the loop's increment. } else // Since this undeclared local variable has the same name as a global, there's // a chance the user intended it to be global. So consider warning the user: MaybeWarnLocalSameAsGlobal(aFunc, var); } } #ifndef MINIDLL LPTSTR Script::ListVars(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates this script's list of variables into text equivalent, putting the result // into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; Func *current_func = g->CurrentFunc ? g->CurrentFunc : g->CurrentFuncGosub; if (current_func) { // This definition might help compiler string pooling by ensuring it stays the same for both usages: #define LIST_VARS_UNDERLINE _T("\r\n--------------------------------------------------\r\n") // Start at the oldest and continue up through the newest: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Static Variables for %s()%s"), current_func->mName, LIST_VARS_UNDERLINE); Func &func = *current_func; // For performance. for (int i = 0; i < func.mStaticVarCount; ++i) if (func.mStaticVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars. aBuf = func.mStaticVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true); // Start at the oldest and continue up through the newest: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\r\n\r\nLocal Variables for %s()%s"), current_func->mName, LIST_VARS_UNDERLINE); for (int i = 0; i < func.mVarCount; ++i) if (func.mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars. aBuf = func.mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true); } // v1.0.31: The description "alphabetical" is kept even though it isn't quite true // when the lazy variable list exists, since those haven't yet been sorted into the main list. // However, 99.9% of scripts do not use the lazy list, so it seems too rare to worry about other // than document it in the ListVars command in the help file: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%sGlobal Variables (alphabetical)%s") , current_func ? _T("\r\n\r\n") : _T(""), LIST_VARS_UNDERLINE); // Start at the oldest and continue up through the newest: for (int i = 0; i < mVarCount; ++i) if (mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars. aBuf = mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true); return aBuf; } LPTSTR Script::ListKeyHistory(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates this key history into text equivalent, putting the result // into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; // Needed for the BUF_SPACE_REMAINING macro. // I was initially concerned that GetWindowText() can hang if the target window is // hung. But at least on newer OS's, this doesn't seem to be a problem: MSDN says // "If the window does not have a caption, the return value is a null string. This // behavior is by design. It allows applications to call GetWindowText without hanging // if the process that owns the target window is hung. However, if the target window // is hung and it belongs to the calling application, GetWindowText will hang the // calling application." HWND target_window = GetForegroundWindow(); TCHAR win_title[100]; if (target_window) GetWindowText(target_window, win_title, _countof(win_title)); else *win_title = '\0'; TCHAR timer_list[128] = _T(""); for (ScriptTimer *timer = mFirstTimer; timer != NULL; timer = timer->mNextTimer) if (timer->mEnabled) sntprintfcat(timer_list, _countof(timer_list) - 3, _T("%s "), timer->mLabel->mName); // Allow room for "..." if (*timer_list) { size_t length = _tcslen(timer_list); if (length > (_countof(timer_list) - 5)) tcslcpy(timer_list + length, _T("..."), _countof(timer_list) - length); else if (timer_list[length - 1] == ' ') timer_list[--length] = '\0'; // Remove the last space if there was room enough for it to have been added. } TCHAR LRtext[256]; aBuf += sntprintf(aBuf, aBufSize, _T("Window: %s") //"\r\nBlocks: %u" _T("\r\nKeybd hook: %s") _T("\r\nMouse hook: %s") _T("\r\nEnabled Timers: %u of %u (%s)") //"\r\nInterruptible?: %s" _T("\r\nInterrupted threads: %d%s") _T("\r\nPaused threads: %d of %d (%d layers)") _T("\r\nModifiers (GetKeyState() now) = %s") _T("\r\n") , win_title //, SimpleHeap::GetBlockCount() , g_KeybdHook == NULL ? _T("no") : _T("yes") , g_MouseHook == NULL ? _T("no") : _T("yes") , mTimerEnabledCount, mTimerCount, timer_list //, INTERRUPTIBLE ? "yes" : "no" , g_nThreads > 1 ? g_nThreads - 1 : 0 , g_nThreads > 1 ? _T(" (preempted: they will resume when the current thread finishes)") : _T("") , g_nPausedThreads - (g_array[0].IsPaused && !mAutoExecSectionIsRunning) // Historically thread #0 isn't counted as a paused thread unless the auto-exec section is running but paused. , g_nThreads, g_nLayersNeedingTimer , ModifiersLRToText(GetModifierLRState(true), LRtext)); GetHookStatus(aBuf, BUF_SPACE_REMAINING); aBuf += _tcslen(aBuf); // Adjust for what GetHookStatus() wrote to the buffer. return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, g_KeyHistory ? _T("\r\nPress [F5] to refresh.") : _T("\r\nKey History has been disabled via #KeyHistory 0.")); } #endif ResultType Script::ActionExec(LPTSTR aAction, LPTSTR aParams, LPTSTR aWorkingDir, bool aDisplayErrors , LPTSTR aRunShowMode, HANDLE *aProcess, bool aUpdateLastError, bool aUseRunAs, Var *aOutputVar) // Caller should specify NULL for aParams if it wants us to attempt to parse out params from // within aAction. Caller may specify empty string ("") instead to specify no params at all. // Remember that aAction and aParams can both be NULL, so don't dereference without checking first. // Note: For the Run & RunWait commands, aParams should always be NULL. Params are parsed out of // the aActionString at runtime, here, rather than at load-time because Run & RunWait might contain // dereferenced variable(s), which can only be resolved at runtime. { HANDLE hprocess_local; HANDLE &hprocess = aProcess ? *aProcess : hprocess_local; // To simplify other things. hprocess = NULL; // Init output param if the caller gave us memory to store it. Even if caller didn't, other things below may rely on this being initialized. if (aOutputVar) // Same aOutputVar->Assign(); // Launching nothing is always a success: if (!aAction || !*aAction) return OK; // Make sure this is set to NULL because CreateProcess() won't work if it's the empty string: if (aWorkingDir && !*aWorkingDir) aWorkingDir = NULL; #define IS_VERB(str) ( !_tcsicmp(str, _T("find")) || !_tcsicmp(str, _T("explore")) || !_tcsicmp(str, _T("open"))\ || !_tcsicmp(str, _T("edit")) || !_tcsicmp(str, _T("print")) || !_tcsicmp(str, _T("properties")) ) // Set default items to be run by ShellExecute(). These are also used by the error // reporting at the end, which is why they're initialized even if CreateProcess() works // and there's no need to use ShellExecute(): LPTSTR shell_verb = NULL; LPTSTR shell_action = aAction; LPTSTR shell_params = NULL; /////////////////////////////////////////////////////////////////////////////////// // This next section is done prior to CreateProcess() because when aParams is NULL, // we need to find out whether aAction contains a system verb. /////////////////////////////////////////////////////////////////////////////////// if (aParams) // Caller specified the params (even an empty string counts, for this purpose). { if (IS_VERB(shell_action)) { shell_verb = shell_action; shell_action = aParams; } else shell_params = aParams; } else // Caller wants us to try to parse params out of aAction. { // Find out the "first phrase" in the string to support the special "find" and "explore" operations. LPTSTR phrase; size_t phrase_len; // Set phrase_end to be the location of the first whitespace char, if one exists: LPTSTR phrase_end = StrChrAny(shell_action, _T(" \t")); // Find space or tab. if (phrase_end) // i.e. there is a second phrase. { phrase_len = phrase_end - shell_action; // Create a null-terminated copy of the phrase for comparison. phrase = tmemcpy(talloca(phrase_len + 1), shell_action, phrase_len); phrase[phrase_len] = '\0'; // Firstly, treat anything following '*' as a verb, to support custom verbs like *Compile. if (*phrase == '*') shell_verb = phrase + 1; // Secondly, check for common system verbs like "find" and "edit". else if (IS_VERB(phrase)) shell_verb = phrase; if (shell_verb) // Exclude the verb and its trailing space or tab from further consideration. shell_action += phrase_len + 1; // Otherwise it's not a verb, and may be re-parsed later. } // shell_action will be split into action and params at a later stage if ShellExecuteEx is to be used. } // This is distinct from hprocess being non-NULL because the two aren't always the // same. For example, if the user does "Run, find D:\" or "RunWait, www.yahoo.com", // no new process handle will be available even though the launch was successful: bool success = false; TCHAR system_error_text[512] = _T(""); bool use_runas = aUseRunAs && (!mRunAsUser.IsEmpty() || !mRunAsPass.IsEmpty() || !mRunAsDomain.IsEmpty()); if (use_runas && shell_verb)
tinku99/ahkdll
fb62b78aee84a9a0efc5394d89bbb82a23b50db6
Clear function static, then local vars before globals
diff --git a/source/script.cpp b/source/script.cpp index 57b03de..190f984 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,854 +1,853 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, IT_CALL); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0), mUnresolvedClasses(NULL) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } - // L31: Release objects stored in variables, where possible. + // L31: Release objects stored in variables, where possible and delete vars. int v, i; - for (v = 0; v < mVarCount; v++) - { - // H19 fix not to delete Clipboard wars - if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) - continue; - mVar[v]->ConvertToNonAliasIfNecessary(); - mVar[v]->Free(); - delete mVar[v]; - } - free(mVar); - mVar = NULL; - for (v = 0; v < mLazyVarCount; v++) - { - mLazyVar[v]->ConvertToNonAliasIfNecessary(); - mLazyVar[v]->Free(); - delete mLazyVar[v]; - } - free(mLazyVar); - mLazyVar = NULL; - + // delete static func vars first for (i = 0; i < mFuncCount; i++) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mStaticVarCount; v++) { f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); delete f.mStaticVar[v]; } for (v = 0; v < f.mStaticLazyVarCount; v++) { f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); delete f.mStaticLazyVar[v]; } for (v = 0; v < f.mVarCount; v++) { f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); delete f.mVar[v]; } for (v = 0; v < f.mLazyVarCount; v++) { f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); delete f.mLazyVar[v]; } if (mFunc[i]->mStaticVar) free(mFunc[i]->mStaticVar); if (mFunc[i]->mStaticLazyVarCount) free(mFunc[i]->mStaticLazyVar); if (mFunc[i]->mVarCount) free(mFunc[i]->mVar); if (mFunc[i]->mLazyVarCount) free(mFunc[i]->mLazyVar); - if (mFunc[i]->mGlobalVarCount) - free(mFunc[i]->mGlobalVar); delete mFunc[i]; } + + for (v = 0; v < mVarCount; v++) + { + // H19 fix not to delete Clipboard wars + if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) + continue; + mVar[v]->ConvertToNonAliasIfNecessary(); + mVar[v]->Free(); + delete mVar[v]; + } + free(mVar); + mVar = NULL; + for (v = 0; v < mLazyVarCount; v++) + { + mLazyVar[v]->ConvertToNonAliasIfNecessary(); + mLazyVar[v]->Free(); + delete mLazyVar[v]; + } + free(mLazyVar); + mLazyVar = NULL; // Destroy Labels for (Label *label = mFirstLabel,*nextLabel = NULL; label;) { nextLabel = label->mNextLabel; delete label; label = nextLabel; } // Destroy Groups for (WinGroup *group = mFirstGroup, *nextGroup = NULL; group;) { nextGroup = group->mNextGroup; delete group; group = nextGroup; } for (Line *line = g_script.mLastLine, *nextLine = NULL; line;) { nextLine = line->mPrevLine; line->FreeDerefBufIfLarge(); delete line; line = nextLine; } Script::~Script(); // destroy main script before resetting variables mVarCount = 0; mVarCountMax = 0; mLazyVarCount = 0; mFuncCount = 0; mFuncCountMax = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; mCombinedLineNumber = 0; #ifndef MINIDLL for (UserMenu *menu = mFirstMenu;menu;) { menu->Destroy(); menu = menu->mNextMenu; } mFirstMenu = NULL; mLastMenu = NULL; mTrayIconTip = NULL; mPriorHotkeyStartTime = 0; #endif mFirstGroup = NULL; mLastGroup = NULL; mFirstTimer = NULL; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; g_NoTrayIcon = false; #endif g_MainTimerExists = false; g_AutoExecTimerExists = false; #ifndef MINIDLL g_InputTimerExists = false; #endif g_DerefTimerExists = false; g_SoundWasPlayed = false; #ifndef MINIDLL g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif g_DeferMessagesForUnderlyingPump = false; g_nLayersNeedingTimer = 0; g_nThreads = 0; g_nPausedThreads = 0; g_MaxThreadsTotal = MAX_THREADS_DEFAULT; #ifndef MINIDLL g_MaxHistoryKeys = 40; g_MaxThreadsPerHotkey = 1; g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. g_InputLevel = 0; #ifndef MINIDLL g_HotCriterion = HOT_NO_CRITERION; g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, g_HotWinText = _T(""); // these are initialized for maintainability. g_FirstHotCriterion = NULL; g_LastHotCriterion = NULL; g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. g_HotExprLineCount = 0; // Number of expression lines currently present. g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. g_HotExprLFW = NULL; // Last Found Window of last #if expression. g_MenuIsVisible = MENU_TYPE_NONE; g_guiCount = 0; // g_guiCountMax = 0; no need because we use realloc for g_gui #ifndef MINIDLL g_HSPriority = 0; // default priority is always 0 g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. g_HSCaseSensitive = false; g_HSConformToCase = true; g_HSDoBackspace = true; g_HSOmitEndChar = false; g_HSSendRaw = false; g_HSEndCharRequired = true; g_HSDetectWhenInsideWord = false; g_HSDoReset = false; g_HSResetUponMouseClick = true; _tcscpy(g_EndChars,_T("-()[]{}:;'\"/\\,.?!\n \t")); // Hotstring default end chars, including a space. #endif g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL g_ForceKeybdHook = false; #endif g_ForceNumLock = NEUTRAL; g_ForceCapsLock = NEUTRAL; g_ForceScrollLock = NEUTRAL; g_BlockInputMode = TOGGLE_DEFAULT; g_BlockInput = false; g_BlockMouseMove = false; #endif #ifndef MINIDLL g_KeyHistoryNext = 0; #ifdef ENABLE_KEY_HISTORY_FILE g_KeyHistoryToFile = false; #endif g_HistoryTickNow = 0; g_HistoryTickPrev = GetTickCount(); // So that the first logged key doesn't have a huge elapsed time. g_HistoryHwndPrev = NULL; #endif g_DefaultScriptCodepage = CP_ACP; g_DestroyWindowCalled = false; g_hWnd = NULL; g_hWndEdit = NULL; g_hFontEdit = NULL; #ifndef MINIDLL g_hWndSplash = NULL; g_hFontSplash = NULL; // So that font can be deleted on program close. #endif g_StrCmpLogicalW = NULL; g_TabClassProc = NULL; g_modifiersLR_logical = 0; g_modifiersLR_logical_non_ignored = 0; g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL g_mouse_buttons_logical = 0; #endif g_BlockWinKeys = false; g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. g_IgnoreNextLControlDown = 0; // g_IgnoreNextLControlUp = 0; // g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. g_ClipboardTimeout = 1000; // v1.0.31 g_KeybdHook = NULL; g_MouseHook = NULL; g_PlaybackHook = NULL; g_ForceLaunch = false; g_WinActivateForce = false; g_Warn_UseUnsetLocal = WARNMODE_OFF; g_Warn_UseUnsetGlobal = WARNMODE_OFF; g_Warn_UseEnv = WARNMODE_OFF; g_Warn_LocalSameAsGlobal = WARNMODE_OFF; #ifndef MINIDLL g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in g_NoEnv = TRUE; // HotKeyIt H5 new default // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined = g_MaxVarCapacity = 64 * 1024 * 1024; #ifndef MINIDLL //g_ScreenDPI = GetScreenDPI(); HDC hdc = GetDC(NULL); g_ScreenDPI = GetDeviceCaps(hdc, LOGPIXELSX); ReleaseDC(NULL, hdc); g_guiCount = 0; #endif g_delimiter = ','; g_DerefChar = '%'; g_EscapeChar = '`'; g_ContinuationLTrim = false; for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //Line::sMaxSourceFiles = 0; //SimpleHeap::Delete(Line::sSourceFile); //Line::sSourceFile = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); DestroyWindow(g_hWndEdit); DeleteObject(g_hFontEdit); #ifndef MINIDLL if (g_hWndSplash) DestroyWindow(g_hWndSplash); if (g_hFontSplash) DeleteObject(g_hFontSplash); #endif } #ifndef MINIDLL // AddRemoveHooks(0); // done in ~Script Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif SimpleHeap::DeleteAll(); DeleteCriticalSection(&g_CriticalHeapBlocks); // g_CriticalHeapBlocks is used in simpleheap for thread-safety. DeleteCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment. mIsReadyToExecute = false; ZeroMemory(&g_script,sizeof(g_script)); #ifndef MINIDLL mPriorHotkeyName = mThisHotkeyName = _T(""); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; } break; // No more switches allowed after this point. } } } LocalFree(dllargv); } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater())
tinku99/ahkdll
56854af8529c17f306631f327d0db3366d6324db
modified: .gitignore
diff --git a/.gitignore b/.gitignore index 2ccc72f..a786639 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,10 @@ AutoHotkey.sdf +*.opensdf +*.suo AutoHotkey.suo AutoHotkey.vcxproj.user ComServer_h.h ComServer_i.c bin ipch temp diff --git a/AutoHotkey.sln b/AutoHotkey.sln index d28ab86..05816f1 100644 --- a/AutoHotkey.sln +++ b/AutoHotkey.sln @@ -1,156 +1,156 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_pcre", "source\lib_pcre\lib_pcre.vcxproj", "{39037993-9571-4DF2-8E39-CD2909043574}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AutoHotkey", "AutoHotkey.vcxproj", "{31335317-2533-40F5-ACD8-361075C7C4CC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug(mbcs)|Win32 = Debug(mbcs)|Win32 - Debug(mbcs)|x64 = Debug(mbcs)|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - DebugDll|Win32 = DebugDll|Win32 - DebugDll|x64 = DebugDll|x64 - Release(mbcs)|Win32 = Release(mbcs)|Win32 - Release(mbcs)|x64 = Release(mbcs)|x64 - Release(minimal)|Win32 = Release(minimal)|Win32 - Release(minimal)|x64 = Release(minimal)|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - ReleaseDll(mbcs)|Win32 = ReleaseDll(mbcs)|Win32 - ReleaseDll(mbcs)|x64 = ReleaseDll(mbcs)|x64 - ReleaseDll|Win32 = ReleaseDll|Win32 - ReleaseDll|x64 = ReleaseDll|x64 - ReleaseDllMini(mbcs)|Win32 = ReleaseDllMini(mbcs)|Win32 - ReleaseDllMini(mbcs)|x64 = ReleaseDllMini(mbcs)|x64 - ReleaseDllMini|Win32 = ReleaseDllMini|Win32 - ReleaseDllMini|x64 = ReleaseDllMini|x64 - Self-contained(debug)|Win32 = Self-contained(debug)|Win32 - Self-contained(debug)|x64 = Self-contained(debug)|x64 - Self-contained(mbcs)|Win32 = Self-contained(mbcs)|Win32 - Self-contained(mbcs)|x64 = Self-contained(mbcs)|x64 - Self-contained(minimal)|Win32 = Self-contained(minimal)|Win32 - Self-contained(minimal)|x64 = Self-contained(minimal)|x64 - Self-contained|Win32 = Self-contained|Win32 - Self-contained|x64 = Self-contained|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.ActiveCfg = Debug|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.Build.0 = Debug|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.ActiveCfg = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.Build.0 = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.ActiveCfg = Debug|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.Build.0 = Debug|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.ActiveCfg = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.Build.0 = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.Build.0 = Release(minimal)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.ActiveCfg = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.Build.0 = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.ActiveCfg = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.Build.0 = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.ActiveCfg = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.Build.0 = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.ActiveCfg = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.Build.0 = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.ActiveCfg = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.Build.0 = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.ActiveCfg = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.Build.0 = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.ActiveCfg = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.Build.0 = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.ActiveCfg = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.Build.0 = Debug|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.Build.0 = Release(minimal)|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.ActiveCfg = Release(minimal)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.Build.0 = Release(minimal)|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.ActiveCfg = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.Build.0 = Release|Win32 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.ActiveCfg = Release|x64 - {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.Build.0 = Release|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.ActiveCfg = Debug|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.Build.0 = Debug|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.ActiveCfg = Debug|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.Build.0 = Debug|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.ActiveCfg = DebugDll|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.Build.0 = DebugDll|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.ActiveCfg = DebugDll|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.Build.0 = DebugDll|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.Build.0 = Release(minimal)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.ActiveCfg = Release|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.Build.0 = Release|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.ActiveCfg = Release|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.Build.0 = Release|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.ActiveCfg = ReleaseDll(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.Build.0 = ReleaseDll(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.ActiveCfg = ReleaseDll|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.Build.0 = ReleaseDll|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.ActiveCfg = ReleaseDll|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.Build.0 = ReleaseDll|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = ReleaseDllMini(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.Build.0 = ReleaseDllMini(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.Build.0 = Release(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.ActiveCfg = ReleaseDllMini|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.Build.0 = ReleaseDllMini|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.ActiveCfg = ReleaseDllMini|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.Build.0 = ReleaseDllMini|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.ActiveCfg = Self-contained(debug)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.Build.0 = Self-contained(debug)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.ActiveCfg = Self-contained(debug)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.Build.0 = Self-contained(debug)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.ActiveCfg = Self-contained(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.Build.0 = Self-contained(mbcs)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.ActiveCfg = Self-contained(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.Build.0 = Self-contained(mbcs)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.ActiveCfg = Self-contained(minimal)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.Build.0 = Self-contained(minimal)|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.ActiveCfg = Self-contained(minimal)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.Build.0 = Self-contained(minimal)|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.ActiveCfg = Self-contained|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.Build.0 = Self-contained|Win32 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.ActiveCfg = Self-contained|x64 - {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.Build.0 = Self-contained|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_pcre", "source\lib_pcre\lib_pcre.vcxproj", "{39037993-9571-4DF2-8E39-CD2909043574}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AutoHotkey", "AutoHotkey.vcxproj", "{31335317-2533-40F5-ACD8-361075C7C4CC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug(mbcs)|Win32 = Debug(mbcs)|Win32 + Debug(mbcs)|x64 = Debug(mbcs)|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + DebugDll|Win32 = DebugDll|Win32 + DebugDll|x64 = DebugDll|x64 + Release(mbcs)|Win32 = Release(mbcs)|Win32 + Release(mbcs)|x64 = Release(mbcs)|x64 + Release(minimal)|Win32 = Release(minimal)|Win32 + Release(minimal)|x64 = Release(minimal)|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseDll(mbcs)|Win32 = ReleaseDll(mbcs)|Win32 + ReleaseDll(mbcs)|x64 = ReleaseDll(mbcs)|x64 + ReleaseDll|Win32 = ReleaseDll|Win32 + ReleaseDll|x64 = ReleaseDll|x64 + ReleaseDllMini(mbcs)|Win32 = ReleaseDllMini(mbcs)|Win32 + ReleaseDllMini(mbcs)|x64 = ReleaseDllMini(mbcs)|x64 + ReleaseDllMini|Win32 = ReleaseDllMini|Win32 + ReleaseDllMini|x64 = ReleaseDllMini|x64 + Self-contained(debug)|Win32 = Self-contained(debug)|Win32 + Self-contained(debug)|x64 = Self-contained(debug)|x64 + Self-contained(mbcs)|Win32 = Self-contained(mbcs)|Win32 + Self-contained(mbcs)|x64 = Self-contained(mbcs)|x64 + Self-contained(minimal)|Win32 = Self-contained(minimal)|Win32 + Self-contained(minimal)|x64 = Self-contained(minimal)|x64 + Self-contained|Win32 = Self-contained|Win32 + Self-contained|x64 = Self-contained|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.ActiveCfg = Debug|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug|Win32.Build.0 = Debug|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.ActiveCfg = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Debug|x64.Build.0 = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.ActiveCfg = Debug|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|Win32.Build.0 = Debug|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.ActiveCfg = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.DebugDll|x64.Build.0 = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release(minimal)|x64.Build.0 = Release(minimal)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.ActiveCfg = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release|Win32.Build.0 = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.ActiveCfg = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Release|x64.Build.0 = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll(mbcs)|x64.Build.0 = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.ActiveCfg = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|Win32.Build.0 = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.ActiveCfg = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDll|x64.Build.0 = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini(mbcs)|x64.Build.0 = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.ActiveCfg = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|Win32.Build.0 = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.ActiveCfg = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.ReleaseDllMini|x64.Build.0 = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.ActiveCfg = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|Win32.Build.0 = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.ActiveCfg = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(debug)|x64.Build.0 = Debug|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(mbcs)|x64.Build.0 = Release(mbcs)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|Win32.Build.0 = Release(minimal)|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.ActiveCfg = Release(minimal)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained(minimal)|x64.Build.0 = Release(minimal)|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.ActiveCfg = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|Win32.Build.0 = Release|Win32 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.ActiveCfg = Release|x64 + {39037993-9571-4DF2-8E39-CD2909043574}.Self-contained|x64.Build.0 = Release|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.ActiveCfg = Debug(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|Win32.Build.0 = Debug(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.ActiveCfg = Debug(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug(mbcs)|x64.Build.0 = Debug(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.ActiveCfg = Debug|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|Win32.Build.0 = Debug|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.ActiveCfg = Debug|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Debug|x64.Build.0 = Debug|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.ActiveCfg = DebugDll|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|Win32.Build.0 = DebugDll|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.ActiveCfg = DebugDll|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.DebugDll|x64.Build.0 = DebugDll|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.ActiveCfg = Release(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|Win32.Build.0 = Release(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.ActiveCfg = Release(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(mbcs)|x64.Build.0 = Release(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.ActiveCfg = Release(minimal)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|Win32.Build.0 = Release(minimal)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.ActiveCfg = Release(minimal)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release(minimal)|x64.Build.0 = Release(minimal)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.ActiveCfg = Release|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|Win32.Build.0 = Release|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.ActiveCfg = Release|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Release|x64.Build.0 = Release|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.ActiveCfg = ReleaseDll(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|Win32.Build.0 = ReleaseDll(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.ActiveCfg = ReleaseDll(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll(mbcs)|x64.Build.0 = ReleaseDll(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.ActiveCfg = ReleaseDll|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|Win32.Build.0 = ReleaseDll|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.ActiveCfg = ReleaseDll|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDll|x64.Build.0 = ReleaseDll|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.ActiveCfg = ReleaseDllMini(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|Win32.Build.0 = ReleaseDllMini(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.ActiveCfg = ReleaseDllMini(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini(mbcs)|x64.Build.0 = ReleaseDllMini(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.ActiveCfg = ReleaseDllMini|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|Win32.Build.0 = ReleaseDllMini|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.ActiveCfg = ReleaseDllMini|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.ReleaseDllMini|x64.Build.0 = ReleaseDllMini|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.ActiveCfg = Self-contained(debug)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|Win32.Build.0 = Self-contained(debug)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.ActiveCfg = Self-contained(debug)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(debug)|x64.Build.0 = Self-contained(debug)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.ActiveCfg = Self-contained(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|Win32.Build.0 = Self-contained(mbcs)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.ActiveCfg = Self-contained(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(mbcs)|x64.Build.0 = Self-contained(mbcs)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.ActiveCfg = Self-contained(minimal)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|Win32.Build.0 = Self-contained(minimal)|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.ActiveCfg = Self-contained(minimal)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained(minimal)|x64.Build.0 = Self-contained(minimal)|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.ActiveCfg = Self-contained|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|Win32.Build.0 = Self-contained|Win32 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.ActiveCfg = Self-contained|x64 + {31335317-2533-40F5-ACD8-361075C7C4CC}.Self-contained|x64.Build.0 = Self-contained|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/AutoHotkey.vcxproj b/AutoHotkey.vcxproj index d7f774b..17116f3 100644 --- a/AutoHotkey.vcxproj +++ b/AutoHotkey.vcxproj @@ -1,1053 +1,1050 @@ -<?xml version="1.0" encoding="utf-8"?> -<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> - <PropertyGroup> - <ProjectGuid>{31335317-2533-40F5-ACD8-361075C7C4CC}</ProjectGuid> - <Keyword>Win32Proj</Keyword> - </PropertyGroup> - <PropertyGroup> - <TargetName>AutoHotkey</TargetName> - <ConfigurationType>Application</ConfigurationType> - <TargetName Condition="'$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDllMini(mbcs)'">AutoHotkeyMini</TargetName> - <ConfigurationType Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">DynamicLibrary</ConfigurationType> - </PropertyGroup> - <ItemGroup Label="ProjectConfigurations"> - <ProjectConfiguration Include="DebugDll|Win32"> - <Configuration>DebugDll</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="DebugDll|x64"> - <Configuration>DebugDll</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Debug|Win32"> - <Configuration>Debug</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Debug|x64"> - <Configuration>Debug</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Debug(mbcs)|Win32"> - <Configuration>Debug(mbcs)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Debug(mbcs)|x64"> - <Configuration>Debug(mbcs)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDll(mbcs)|Win32"> - <Configuration>ReleaseDll(mbcs)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDll(mbcs)|x64"> - <Configuration>ReleaseDll(mbcs)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDllMini(mbcs)|Win32"> - <Configuration>ReleaseDllMini(mbcs)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDllMini(mbcs)|x64"> - <Configuration>ReleaseDllMini(mbcs)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDllMini|Win32"> - <Configuration>ReleaseDllMini</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDllMini|x64"> - <Configuration>ReleaseDllMini</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDll|Win32"> - <Configuration>ReleaseDll</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="ReleaseDll|x64"> - <Configuration>ReleaseDll</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release|Win32"> - <Configuration>Release</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release|x64"> - <Configuration>Release</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release(mbcs)|Win32"> - <Configuration>Release(mbcs)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release(mbcs)|x64"> - <Configuration>Release(mbcs)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release(minimal)|Win32"> - <Configuration>Release(minimal)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Release(minimal)|x64"> - <Configuration>Release(minimal)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained|Win32"> - <Configuration>Self-contained</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained|x64"> - <Configuration>Self-contained</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(debug)|Win32"> - <Configuration>Self-contained(debug)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(debug)|x64"> - <Configuration>Self-contained(debug)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(mbcs)|Win32"> - <Configuration>Self-contained(mbcs)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(mbcs)|x64"> - <Configuration>Self-contained(mbcs)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(minimal)|Win32"> - <Configuration>Self-contained(minimal)</Configuration> - <Platform>Win32</Platform> - </ProjectConfiguration> - <ProjectConfiguration Include="Self-contained(minimal)|x64"> - <Configuration>Self-contained(minimal)</Configuration> - <Platform>x64</Platform> - </ProjectConfiguration> - </ItemGroup> - <PropertyGroup Label="Globals"> - <ProjectName>AutoHotkey</ProjectName> - </PropertyGroup> - <!-- x64 toolset: must precede the import below --> - <PropertyGroup Label="Configuration" Condition="'$(Platform)'=='x64'"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" Label="Configuration"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" Label="Configuration"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" Label="Configuration"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> - <PlatformToolset> - </PlatformToolset> - <UseOfMfc>false</UseOfMfc> - <UseOfAtl>false</UseOfAtl> - <CharacterSet /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" Label="Configuration"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - <PlatformToolset> - </PlatformToolset> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'"> - <PlatformToolset /> - </PropertyGroup> - <!-- import common config --> - <Import Project="Config.vcxproj" /> - <!-- platform: win32 & x64 (common) --> - <ItemDefinitionGroup Condition="'$(Platform)'=='Win32' OR '$(Platform)'=='x64'"> - <ClCompile> - <PreprocessorDefinitions>_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ClCompile> - <Link> - <SubSystem>Windows</SubSystem> - <AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies> - <StackReserveSize>4194304</StackReserveSize> - <TerminalServerAware>false</TerminalServerAware> - </Link> - </ItemDefinitionGroup> - <!-- platform: win32 --> - <ItemDefinitionGroup Condition="'$(Platform)'=='Win32'"> - <Link> - <TargetMachine>MachineX86</TargetMachine> - <MinimumRequiredVersion>5</MinimumRequiredVersion> - </Link> - </ItemDefinitionGroup> - <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='DebugDll'"> - <ClCompile> - <PreprocessorDefinitions>_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ClCompile> - </ItemDefinitionGroup> - <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='ReleaseDllMini'"> - <ClCompile> - <PreprocessorDefinitions>_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ClCompile> - </ItemDefinitionGroup> - <!-- platform: x64 --> - <ItemDefinitionGroup Condition="'$(Platform)'=='x64'"> - <ClCompile> - <PreprocessorDefinitions>_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ClCompile> - <Link> - <TargetMachine>MachineX64</TargetMachine> - </Link> - </ItemDefinitionGroup> - <!-- paths and basic settings --> - <PropertyGroup> - <IntDir>temp\$(Platform)\$(Configuration)\</IntDir> - <BinDir>bin\$(Platform)</BinDir> - <BinDir Condition="'$(CharacterSet)'=='Unicode'">$(BinDir)w</BinDir> - <BinDir Condition="'$(CharacterSet)'=='MultiByte'">$(BinDir)a</BinDir> - <OutDir>$(BinDir)\</OutDir> - <OutDir Condition="$(ConfigDebug)">$(BinDir)_debug\</OutDir> - <OutDir Condition="$(ConfigMinSize)">$(BinDir)_minimal\</OutDir> - </PropertyGroup> - <ItemDefinitionGroup> - <ClCompile> - <PrecompiledHeader Condition="!$(ConfigDebug)">Use</PrecompiledHeader> - </ClCompile> - <Link> - <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile> - </Link> - <Manifest> - <AdditionalManifestFiles>source\resources\AutoHotkey.exe.manifest;%(AdditionalManifestFiles)</AdditionalManifestFiles> - </Manifest> - </ItemDefinitionGroup> - <!-- self-contained: required settings --> - <PropertyGroup Condition="$(ConfigSC)"> - <TargetName>AutoHotkeySC</TargetName> - <TargetExt>.bin</TargetExt> - </PropertyGroup> - <ItemDefinitionGroup Condition="$(ConfigSC)"> - <ClCompile> - <PreprocessorDefinitions>AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ClCompile> - <ResourceCompile> - <PreprocessorDefinitions>_WIN64;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <PreprocessorDefinitions Condition="$(ConfigDebug)">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <Link> - <AdditionalDependencies Condition="'$(Platform)'=='Win32'">%(AdditionalDependencies)</AdditionalDependencies> - </Link> - <PostBuildEvent> - <Message>Removing CheckSum from $(TargetFileName) so Ahk2Exe doesn't complain</Message> - <Command>"$(ProjectDir)PostBuildSC.ahk" "$(TargetPath)"</Command> - </PostBuildEvent> - </ItemDefinitionGroup> - <!-- upx compression: Release --> - <PropertyGroup> - <PackerName>upx</PackerName> - <PackerName Condition="'$(Platform)'=='x64'">mpress</PackerName> - <PackerPath Condition="'$(PackerPath)'=='' AND exists('$(PackerName).exe')">$(PackerName).exe</PackerPath> - <PackerPath Condition="'$(PackerPath)'=='' AND exists('..\$(PackerName).exe')">..\$(PackerName).exe</PackerPath> - <PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='upx'"> --best --no-lzma --filter=73 --compress-icons=0</PackerArgs> - <PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='mpress'"> -x</PackerArgs> - </PropertyGroup> - <ItemDefinitionGroup Condition="$(ConfigRelease)"> - <PostBuildEvent> - <Command>echo $(PackerName).exe disabled or not found, skipping compression</Command> - <Command Condition="exists('$(PackerPath)')">$(PackerPath)$(PackerArgs) "$(TargetPath)" &amp; exit 0</Command> - </PostBuildEvent> - </ItemDefinitionGroup> - <!-- Visual C++ 2010 should place any newly created properties in these groups --> - <!-- FILES --> - <ItemGroup> - <ClCompile Include="source\application.cpp" /> - <ClCompile Include="source\AutoHotkey.cpp" /> - <ClCompile Include="source\clipboard.cpp" /> - <ClCompile Include="source\Debugger.cpp"> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Speed</FavorSizeOrSpeed> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Speed</FavorSizeOrSpeed> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">NotUsing</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">NotUsing</PrecompiledHeader> - </ClCompile> - <ClCompile Include="source\dllmain.cpp" /> - <ClCompile Include="source\exports.cpp" /> - <ClCompile Include="source\globaldata.cpp" /> - <ClCompile Include="source\hook.cpp" /> - <ClCompile Include="source\hotkey.cpp" /> - <ClCompile Include="source\keyboard_mouse.cpp" /> - <ClCompile Include="source\lowlevelbif.cpp" /> - <ClCompile Include="source\MemoryModule.cpp"> - <PrecompiledHeader>NotUsing</PrecompiledHeader> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">DEBUG_OUTPUT;_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> - </UndefinePreprocessorDefinitions> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild> - <BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">EnableFastChecks</BasicRuntimeChecks> - <FunctionLevelLinking Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> - </FunctionLevelLinking> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">DEBUG_OUTPUT;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">_MBCS;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'"> - </UndefinePreprocessorDefinitions> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </UndefinePreprocessorDefinitions> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Use</PrecompiledHeader> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'"> - </UndefinePreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'"> - </UndefinePreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'"> - </UndefinePreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'"> - </UndefinePreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'"> - </UndefinePreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'"> - </UndefinePreprocessorDefinitions> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Use</PrecompiledHeader> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Use</PrecompiledHeader> - </ClCompile> - <ClCompile Include="source\mt19937ar-cok.cpp" /> - <ClCompile Include="source\os_version.cpp" /> - <ClCompile Include="source\Registry.cpp"> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader> - </ClCompile> - <ClCompile Include="source\script.cpp" /> - <ClCompile Include="source\script2.cpp" /> - <ClCompile Include="source\script_autoit.cpp" /> - <ClCompile Include="source\script_com.cpp" /> - <ClCompile Include="source\script_expression.cpp" /> - <ClCompile Include="source\script_gui.cpp" /> - <ClCompile Include="source\script_menu.cpp" /> - <ClCompile Include="source\script_object.cpp" /> - <ClCompile Include="source\script_object_bif.cpp" /> - <ClCompile Include="source\script_registry.cpp" /> - <ClCompile Include="source\script_struct.cpp" /> - <ClCompile Include="source\SimpleHeap.cpp" /> - <ClCompile Include="source\stdafx.cpp"> - <PrecompiledHeader>Create</PrecompiledHeader> - </ClCompile> - <ClCompile Include="source\StringConv.cpp" /> - <ClCompile Include="source\TextIO.cpp" /> - <ClCompile Include="source\util.cpp" /> - <ClCompile Include="source\var.cpp" /> - <ClCompile Include="source\window.cpp" /> - <ClCompile Include="source\WinGroup.cpp" /> - </ItemGroup> - <ItemGroup> - <ClInclude Include="source\ahkversion.h" /> - <ClInclude Include="source\application.h" /> - <ClInclude Include="source\ComServerImpl.h" /> - <ClInclude Include="source\clipboard.h" /> - <ClInclude Include="source\config.h" /> - <ClInclude Include="source\debug.h" /> - <ClInclude Include="source\Debugger.h" /> - <ClInclude Include="source\defines.h" /> - <ClInclude Include="source\exports.h" /> - <ClInclude Include="source\lib\exearc_read.h" /> - <ClInclude Include="source\globaldata.h" /> - <ClInclude Include="source\hook.h" /> - <ClInclude Include="source\hotkey.h" /> - <ClInclude Include="source\keyboard_mouse.h" /> - <ClInclude Include="source\KuString.h" /> - <ClInclude Include="source\MemoryModule.h" /> - <ClInclude Include="source\mt19937ar-cok.h" /> - <ClInclude Include="source\os_version.h" /> - <ClInclude Include="source\lib_pcre\pcre\pcre.h" /> - <ClInclude Include="source\qmath.h" /> - <ClInclude Include="source\Registry.h" /> - <ClInclude Include="source\resources\resource.h" /> - <ClInclude Include="source\script.h" /> - <ClInclude Include="source\script_com.h" /> - <ClInclude Include="source\script_object.h" /> - <ClInclude Include="source\SimpleHeap.h" /> - <ClInclude Include="source\stdafx.h" /> - <ClInclude Include="source\StringConv.h" /> - <ClInclude Include="source\TextIO.h" /> - <ClInclude Include="source\util.h" /> - <ClInclude Include="source\var.h" /> - <ClInclude Include="source\window.h" /> - <ClInclude Include="source\WinGroup.h" /> - </ItemGroup> - <PropertyGroup> - <Masm>ml</Masm> - <Masm Condition="'$(Platform)'=='x64'">ml64</Masm> - <TargetExt>.exe</TargetExt> - <TargetExt Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">.dll</TargetExt> - <TargetExt Condition="'$(Configuration)'=='Self-contained(mbcs)' OR '$(Configuration)'=='Self-contained'">.bin</TargetExt> - <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental> - <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</LinkIncremental> - <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IgnoreImportLibrary> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> - </ReferencePath> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> - <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> - <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'" /> - <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> - <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> - </PropertyGroup> - <ItemDefinitionGroup> - <CustomBuild> - <Command>$(Masm) /Cx /Fo"$(SolutionDir)temp\$(Platform)\%(Filename).obj" /c "%(FullPath)"</Command> - <Message /> - <Outputs>$(SolutionDir)temp\$(Platform)\%(Filename).obj</Outputs> - </CustomBuild> - <ClCompile> - <Optimization Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Disabled</Optimization> - </ClCompile> - <ClCompile> - <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Neither</FavorSizeOrSpeed> - </ClCompile> - <ClCompile> - <OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</OmitFramePointers> - <StringPooling Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </StringPooling> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</MinimalRebuild> - <BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">EnableFastChecks</BasicRuntimeChecks> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">MultiThreadedDLL</RuntimeLibrary> - <BufferSecurityCheck Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</BufferSecurityCheck> - <EnableFiberSafeOptimizations Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</EnableFiberSafeOptimizations> - <IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IntrinsicFunctions> - <CreateHotpatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </CreateHotpatchableImage> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</MultiProcessorCompilation> - </ClCompile> - <Link> - <GenerateDebugInformation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</GenerateDebugInformation> - <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">.\comserver.def</ModuleDefinitionFile> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </ImportLibrary> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</DataExecutionPrevention> - <CreateHotPatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </CreateHotPatchableImage> - <HeapReserveSize Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </HeapReserveSize> - <Driver Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotSet</Driver> - <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </OptimizeReferences> - <LinkTimeCodeGeneration Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </LinkTimeCodeGeneration> - <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </EnableCOMDATFolding> - </Link> - <Link> - <ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'"> - </ImportLibrary> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> - </ImportLibrary> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> - </ImportLibrary> - <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</OptimizeReferences> - <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</OptimizeReferences> - <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</OptimizeReferences> - <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</OptimizeReferences> - <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</EnableCOMDATFolding> - <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</EnableCOMDATFolding> - <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</EnableCOMDATFolding> - <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</EnableCOMDATFolding> - <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</DataExecutionPrevention> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</DataExecutionPrevention> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</DataExecutionPrevention> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> - </IgnoreAllDefaultLibraries> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> - </IgnoreAllDefaultLibraries> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'"> - </IgnoreAllDefaultLibraries> - </Link> - <Midl> - <MkTypLibCompatible Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</MkTypLibCompatible> - </Midl> - <Link> - <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(TargetName).lib</ImportLibrary> - <ProgramDatabaseFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)$(TargetName).pdb</ProgramDatabaseFile> - </Link> - <Manifest> - <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> - </OutputManifestFile> - <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> - <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> - <RegistrarScriptFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> - <ReplacementsFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> - </Manifest> - <Midl> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </Midl> - <Midl> - <MkTypLibCompatible Condition="'$(Configuration)'=='DebugDll' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDll(mbcs)'">true</MkTypLibCompatible> - <GenerateTypeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateTypeLibrary> - </Midl> - <ClCompile> - <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader> - <ProgramDataBaseFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</ProgramDataBaseFileName> - </ClCompile> - <Manifest> - <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> - <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> - <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> - <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> - </Manifest> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">_DEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <Link> - <ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile> - </Link> - <Link> - <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> - <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'" /> - <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'" /> - <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">.\comserver.def</ModuleDefinitionFile> - </Link> - <Manifest> - <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> - </OutputManifestFile> - </Manifest> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" /> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;_DEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <Link> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</RandomizedBaseAddress> - </Link> - <Link> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</DataExecutionPrevention> - </Link> - <Link> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</RandomizedBaseAddress> - </Link> - <Link> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</DataExecutionPrevention> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'"> - </IgnoreAllDefaultLibraries> - </Link> - <Link> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</RandomizedBaseAddress> - </Link> - <Link> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</DataExecutionPrevention> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> - </IgnoreAllDefaultLibraries> - </Link> - <Link> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</RandomizedBaseAddress> - </Link> - <Link> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</DataExecutionPrevention> - </Link> - <Link> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</RandomizedBaseAddress> - </Link> - <Link> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</DataExecutionPrevention> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'"> - </IgnoreAllDefaultLibraries> - </Link> - <ClCompile> - <OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</OmitFramePointers> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreadedDLL</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</MultiProcessorCompilation> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild> - </ClCompile> - <ProjectReference> - <UseLibraryDependencyInputs Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</UseLibraryDependencyInputs> - </ProjectReference> - <Bscmake> - <PreserveSBR Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</PreserveSBR> - </Bscmake> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">MultiThreadedDLL</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">false</MultiProcessorCompilation> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">true</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</MultiProcessorCompilation> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">MultiThreadedDLL</RuntimeLibrary> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</MinimalRebuild> - </ClCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</MultiProcessorCompilation> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">MultiThreadedDLL</RuntimeLibrary> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">true</MinimalRebuild> - </ClCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">false</MultiProcessorCompilation> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">MultiThreadedDLL</RuntimeLibrary> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</MinimalRebuild> - </ClCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">false</MultiProcessorCompilation> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">MultiThreadedDLL</RuntimeLibrary> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">true</MinimalRebuild> - </ClCompile> - </ItemDefinitionGroup> - <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDll(mbcs)'"> - <Link> - <AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</DataExecutionPrevention> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</DataExecutionPrevention> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'"> - </IgnoreAllDefaultLibraries> - <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> - </IgnoreAllDefaultLibraries> - <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</RandomizedBaseAddress> - <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</DataExecutionPrevention> - </Link> - <Manifest> - <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> - </OutputManifestFile> - </Manifest> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">_USRDLL</PreprocessorDefinitions> - </ResourceCompile> - <ResourceCompile> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_USRDLL;_UNICODE;UNICODE;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">true</MultiProcessorCompilation> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">MultiThreaded</RuntimeLibrary> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</MultiProcessorCompilation> - <IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</IntrinsicFunctions> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">MultiThreaded</RuntimeLibrary> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</MinimalRebuild> - </ClCompile> - <Midl> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_WIN64</PreprocessorDefinitions> - </Midl> - <Midl> - <TargetEnvironment Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">X64</TargetEnvironment> - </Midl> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</MinimalRebuild> - </ClCompile> - <ClCompile> - <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">MultiThreaded</RuntimeLibrary> - <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">true</MultiProcessorCompilation> - <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">false</TreatWarningAsError> - <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">false</MinimalRebuild> - </ClCompile> - </ItemDefinitionGroup> - <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> - <Link> - <ImportLibrary /> - <RandomizedBaseAddress>false</RandomizedBaseAddress> - <DataExecutionPrevention>false</DataExecutionPrevention> - </Link> - <ClCompile> - <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> - <MultiProcessorCompilation>false</MultiProcessorCompilation> - <MinimalRebuild>true</MinimalRebuild> - </ClCompile> - </ItemDefinitionGroup> - <ItemGroup> - <CustomBuild Include="source\lib\win2kcompat.asm"> - <ExcludedFromBuild Condition="'$(Platform)'!='Win32'">true</ExcludedFromBuild> - </CustomBuild> - <CustomBuild Include="source\libx64call\x64call.asm"> - <ExcludedFromBuild Condition="'$(Platform)'!='x64'">true</ExcludedFromBuild> - </CustomBuild> - <CustomBuild Include="source\libx64call\x64stub.asm"> - <ExcludedFromBuild Condition="'$(Platform)'!='x64'">true</ExcludedFromBuild> - </CustomBuild> - </ItemGroup> - <ItemGroup> - <ResourceCompile Include="source\resources\AutoHotkey.rc"> - <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> - </ResourceCompile> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="source\lib_pcre\lib_pcre.vcxproj"> - <Project>{39037993-9571-4DF2-8E39-CD2909043574}</Project> - <ReferenceOutputAssembly>false</ReferenceOutputAssembly> - <Private>false</Private> - <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies> - <LinkLibraryDependencies>true</LinkLibraryDependencies> - <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs> - </ProjectReference> - </ItemGroup> - <ItemGroup> - <Manifest Include="source\resources\AutoHotkey.exe.manifest" /> - </ItemGroup> - <ItemGroup> - <None Include="ComServer.def"> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> - </None> - <None Include="source\resources\icon_filetype.ico" /> - <None Include="source\resources\icon_main.ico" /> - <None Include="source\resources\icon_pause.ico" /> - <None Include="source\resources\icon_pause_suspend.ico" /> - <None Include="source\resources\icon_suspend.ico" /> - <None Include="source\resources\icon_tray_win9x.ico" /> - <None Include="source\resources\icon_tray_win9x_suspend.ico" /> - </ItemGroup> - <ItemGroup> - <Midl Include="source\ComServer.idl"> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</ExcludedFromBuild> - <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</ExcludedFromBuild> - <TargetEnvironment Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">X64</TargetEnvironment> - </Midl> - </ItemGroup> - <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <ProjectGuid>{31335317-2533-40F5-ACD8-361075C7C4CC}</ProjectGuid> + <Keyword>Win32Proj</Keyword> + </PropertyGroup> + <PropertyGroup> + <TargetName>AutoHotkey</TargetName> + <ConfigurationType>Application</ConfigurationType> + <TargetName Condition="'$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDllMini(mbcs)'">AutoHotkeyMini</TargetName> + <ConfigurationType Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">DynamicLibrary</ConfigurationType> + </PropertyGroup> + <ItemGroup Label="ProjectConfigurations"> + <ProjectConfiguration Include="DebugDll|Win32"> + <Configuration>DebugDll</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="DebugDll|x64"> + <Configuration>DebugDll</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|Win32"> + <Configuration>Debug</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug|x64"> + <Configuration>Debug</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug(mbcs)|Win32"> + <Configuration>Debug(mbcs)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Debug(mbcs)|x64"> + <Configuration>Debug(mbcs)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDll(mbcs)|Win32"> + <Configuration>ReleaseDll(mbcs)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDll(mbcs)|x64"> + <Configuration>ReleaseDll(mbcs)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDllMini(mbcs)|Win32"> + <Configuration>ReleaseDllMini(mbcs)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDllMini(mbcs)|x64"> + <Configuration>ReleaseDllMini(mbcs)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDllMini|Win32"> + <Configuration>ReleaseDllMini</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDllMini|x64"> + <Configuration>ReleaseDllMini</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDll|Win32"> + <Configuration>ReleaseDll</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="ReleaseDll|x64"> + <Configuration>ReleaseDll</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|Win32"> + <Configuration>Release</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release|x64"> + <Configuration>Release</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release(mbcs)|Win32"> + <Configuration>Release(mbcs)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release(mbcs)|x64"> + <Configuration>Release(mbcs)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release(minimal)|Win32"> + <Configuration>Release(minimal)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Release(minimal)|x64"> + <Configuration>Release(minimal)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained|Win32"> + <Configuration>Self-contained</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained|x64"> + <Configuration>Self-contained</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(debug)|Win32"> + <Configuration>Self-contained(debug)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(debug)|x64"> + <Configuration>Self-contained(debug)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(mbcs)|Win32"> + <Configuration>Self-contained(mbcs)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(mbcs)|x64"> + <Configuration>Self-contained(mbcs)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(minimal)|Win32"> + <Configuration>Self-contained(minimal)</Configuration> + <Platform>Win32</Platform> + </ProjectConfiguration> + <ProjectConfiguration Include="Self-contained(minimal)|x64"> + <Configuration>Self-contained(minimal)</Configuration> + <Platform>x64</Platform> + </ProjectConfiguration> + </ItemGroup> + <PropertyGroup Label="Globals"> + <ProjectName>AutoHotkey</ProjectName> + </PropertyGroup> + <!-- x64 toolset: must precede the import below --> + <PropertyGroup Label="Configuration" Condition="'$(Platform)'=='x64'"> + <PlatformToolset>Windows7.1SDK</PlatformToolset> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + <PlatformToolset> + </PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" Label="Configuration"> + <PlatformToolset>v100</PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" Label="Configuration"> + <PlatformToolset> + </PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" Label="Configuration"> + <PlatformToolset> + </PlatformToolset> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <PlatformToolset> + </PlatformToolset> + <UseOfMfc>false</UseOfMfc> + <UseOfAtl>false</UseOfAtl> + <CharacterSet /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'"> + <PlatformToolset> + </PlatformToolset> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" Label="Configuration"> + <PlatformToolset>v100</PlatformToolset> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + <PlatformToolset> + </PlatformToolset> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'"> + <PlatformToolset /> + </PropertyGroup> + <!-- import common config --> + <Import Project="Config.vcxproj" /> + <!-- platform: win32 & x64 (common) --> + <ItemDefinitionGroup Condition="'$(Platform)'=='Win32' OR '$(Platform)'=='x64'"> + <ClCompile> + <PreprocessorDefinitions>_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + <Link> + <SubSystem>Windows</SubSystem> + <AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies> + <StackReserveSize>4194304</StackReserveSize> + <TerminalServerAware>false</TerminalServerAware> + </Link> + </ItemDefinitionGroup> + <!-- platform: win32 --> + <ItemDefinitionGroup Condition="'$(Platform)'=='Win32'"> + <Link> + <TargetMachine>MachineX86</TargetMachine> + <MinimumRequiredVersion>5</MinimumRequiredVersion> + </Link> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='DebugDll'"> + <ClCompile> + <PreprocessorDefinitions>_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='ReleaseDllMini'"> + <ClCompile> + <PreprocessorDefinitions>_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + </ItemDefinitionGroup> + <!-- platform: x64 --> + <ItemDefinitionGroup Condition="'$(Platform)'=='x64'"> + <ClCompile> + <PreprocessorDefinitions>_WIN64;AUTOCOMSERVER_EXPORTS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + <Link> + <TargetMachine>MachineX64</TargetMachine> + </Link> + </ItemDefinitionGroup> + <!-- paths and basic settings --> + <PropertyGroup> + <IntDir>temp\$(Platform)\$(Configuration)\</IntDir> + <BinDir>bin\$(Platform)</BinDir> + <BinDir Condition="'$(CharacterSet)'=='Unicode'">$(BinDir)w</BinDir> + <BinDir Condition="'$(CharacterSet)'=='MultiByte'">$(BinDir)a</BinDir> + <OutDir>$(BinDir)\</OutDir> + <OutDir Condition="$(ConfigDebug)">$(BinDir)_debug\</OutDir> + <OutDir Condition="$(ConfigMinSize)">$(BinDir)_minimal\</OutDir> + </PropertyGroup> + <ItemDefinitionGroup> + <ClCompile> + <PrecompiledHeader Condition="!$(ConfigDebug)">Use</PrecompiledHeader> + </ClCompile> + <Link> + <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile> + </Link> + <Manifest> + <AdditionalManifestFiles>source\resources\AutoHotkey.exe.manifest;%(AdditionalManifestFiles)</AdditionalManifestFiles> + </Manifest> + </ItemDefinitionGroup> + <!-- self-contained: required settings --> + <PropertyGroup Condition="$(ConfigSC)"> + <TargetName>AutoHotkeySC</TargetName> + <TargetExt>.bin</TargetExt> + </PropertyGroup> + <ItemDefinitionGroup Condition="$(ConfigSC)"> + <ClCompile> + <PreprocessorDefinitions>AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ClCompile> + <ResourceCompile> + <PreprocessorDefinitions>_WIN64;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <PreprocessorDefinitions Condition="$(ConfigDebug)">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <AdditionalDependencies Condition="'$(Platform)'=='Win32'">%(AdditionalDependencies)</AdditionalDependencies> + </Link> + <PostBuildEvent> + <Message>Removing CheckSum from $(TargetFileName) so Ahk2Exe doesn't complain</Message> + <Command>"$(ProjectDir)PostBuildSC.ahk" "$(TargetPath)"</Command> + </PostBuildEvent> + </ItemDefinitionGroup> + <!-- upx compression: Release --> + <PropertyGroup> + <PackerName>upx</PackerName> + <PackerName Condition="'$(Platform)'=='x64'">mpress</PackerName> + <PackerPath Condition="'$(PackerPath)'=='' AND exists('$(PackerName).exe')">$(PackerName).exe</PackerPath> + <PackerPath Condition="'$(PackerPath)'=='' AND exists('..\$(PackerName).exe')">..\$(PackerName).exe</PackerPath> + <PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='upx'"> --best --no-lzma --filter=73 --compress-icons=0</PackerArgs> + <PackerArgs Condition="'$(PackerArgs)'=='' AND '$(PackerName)'=='mpress'"> -x</PackerArgs> + </PropertyGroup> + <ItemDefinitionGroup Condition="$(ConfigRelease)"> + <PostBuildEvent> + <Command>echo $(PackerName).exe disabled or not found, skipping compression</Command> + <Command Condition="exists('$(PackerPath)')">$(PackerPath)$(PackerArgs) "$(TargetPath)" &amp; exit 0</Command> + </PostBuildEvent> + </ItemDefinitionGroup> + <!-- Visual C++ 2010 should place any newly created properties in these groups --> + <!-- FILES --> + <ItemGroup> + <ClCompile Include="source\application.cpp" /> + <ClCompile Include="source\AutoHotkey.cpp" /> + <ClCompile Include="source\clipboard.cpp" /> + <ClCompile Include="source\Debugger.cpp"> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Speed</FavorSizeOrSpeed> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Speed</FavorSizeOrSpeed> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">NotUsing</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">NotUsing</PrecompiledHeader> + </ClCompile> + <ClCompile Include="source\dllmain.cpp" /> + <ClCompile Include="source\exports.cpp" /> + <ClCompile Include="source\globaldata.cpp" /> + <ClCompile Include="source\hook.cpp" /> + <ClCompile Include="source\hotkey.cpp" /> + <ClCompile Include="source\keyboard_mouse.cpp" /> + <ClCompile Include="source\lowlevelbif.cpp" /> + <ClCompile Include="source\MemoryModule.cpp"> + <PrecompiledHeader>NotUsing</PrecompiledHeader> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">DEBUG_OUTPUT;_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + </UndefinePreprocessorDefinitions> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild> + <BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">EnableFastChecks</BasicRuntimeChecks> + <FunctionLevelLinking Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> + </FunctionLevelLinking> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">DEBUG_OUTPUT;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">_USRDLL;MINIDLL;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">_MBCS;AUTOHOTKEYSC;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_MBCS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'"> + </UndefinePreprocessorDefinitions> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </UndefinePreprocessorDefinitions> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">Use</PrecompiledHeader> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'"> + </UndefinePreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'"> + </UndefinePreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'"> + </UndefinePreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'"> + </UndefinePreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'"> + </UndefinePreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'"> + </UndefinePreprocessorDefinitions> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">Use</PrecompiledHeader> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">Use</PrecompiledHeader> + </ClCompile> + <ClCompile Include="source\mt19937ar-cok.cpp" /> + <ClCompile Include="source\os_version.cpp" /> + <ClCompile Include="source\Registry.cpp"> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotUsing</PrecompiledHeader> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">NotUsing</PrecompiledHeader> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_MBCS;MBCS;_USRDLL;AUTOCOMSERVER_EXPORTS;_STANDALONE;WIN32;_WINDOWS;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <UndefinePreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_UNICODE;UNICODE</UndefinePreprocessorDefinitions> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">NotUsing</PrecompiledHeader> + </ClCompile> + <ClCompile Include="source\script.cpp" /> + <ClCompile Include="source\script2.cpp" /> + <ClCompile Include="source\script_autoit.cpp" /> + <ClCompile Include="source\script_com.cpp" /> + <ClCompile Include="source\script_expression.cpp" /> + <ClCompile Include="source\script_gui.cpp" /> + <ClCompile Include="source\script_menu.cpp" /> + <ClCompile Include="source\script_object.cpp" /> + <ClCompile Include="source\script_object_bif.cpp" /> + <ClCompile Include="source\script_registry.cpp" /> + <ClCompile Include="source\script_struct.cpp" /> + <ClCompile Include="source\SimpleHeap.cpp" /> + <ClCompile Include="source\stdafx.cpp"> + <PrecompiledHeader>Create</PrecompiledHeader> + </ClCompile> + <ClCompile Include="source\StringConv.cpp" /> + <ClCompile Include="source\TextIO.cpp" /> + <ClCompile Include="source\util.cpp" /> + <ClCompile Include="source\var.cpp" /> + <ClCompile Include="source\window.cpp" /> + <ClCompile Include="source\WinGroup.cpp" /> + </ItemGroup> + <ItemGroup> + <ClInclude Include="source\ahkversion.h" /> + <ClInclude Include="source\application.h" /> + <ClInclude Include="source\ComServerImpl.h" /> + <ClInclude Include="source\clipboard.h" /> + <ClInclude Include="source\config.h" /> + <ClInclude Include="source\debug.h" /> + <ClInclude Include="source\Debugger.h" /> + <ClInclude Include="source\defines.h" /> + <ClInclude Include="source\exports.h" /> + <ClInclude Include="source\lib\exearc_read.h" /> + <ClInclude Include="source\globaldata.h" /> + <ClInclude Include="source\hook.h" /> + <ClInclude Include="source\hotkey.h" /> + <ClInclude Include="source\keyboard_mouse.h" /> + <ClInclude Include="source\KuString.h" /> + <ClInclude Include="source\MemoryModule.h" /> + <ClInclude Include="source\mt19937ar-cok.h" /> + <ClInclude Include="source\os_version.h" /> + <ClInclude Include="source\lib_pcre\pcre\pcre.h" /> + <ClInclude Include="source\qmath.h" /> + <ClInclude Include="source\Registry.h" /> + <ClInclude Include="source\resources\resource.h" /> + <ClInclude Include="source\script.h" /> + <ClInclude Include="source\script_com.h" /> + <ClInclude Include="source\script_object.h" /> + <ClInclude Include="source\SimpleHeap.h" /> + <ClInclude Include="source\stdafx.h" /> + <ClInclude Include="source\StringConv.h" /> + <ClInclude Include="source\TextIO.h" /> + <ClInclude Include="source\util.h" /> + <ClInclude Include="source\var.h" /> + <ClInclude Include="source\window.h" /> + <ClInclude Include="source\WinGroup.h" /> + </ItemGroup> + <PropertyGroup> + <Masm>ml</Masm> + <Masm Condition="'$(Platform)'=='x64'">ml64</Masm> + <TargetExt>.exe</TargetExt> + <TargetExt Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDllMini' OR '$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDllMini(mbcs)' OR '$(Configuration)'=='DebugDll'">.dll</TargetExt> + <TargetExt Condition="'$(Configuration)'=='Self-contained(mbcs)' OR '$(Configuration)'=='Self-contained'">.bin</TargetExt> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental> + <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</LinkIncremental> + <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IgnoreImportLibrary> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + </ReferencePath> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(ExecutablePath);$(WindowsSdkMSBuildTools);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath> + <IncludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(IncludePath);$(VCInstallDir)atlmfc\include</IncludePath> + <ReferencePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'" /> + <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib</LibraryPath> + <ExcludePath Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">$(WindowsSdkDir)include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkMSBuildTools);$(VCInstallDir)atlmfc\lib;$(VCInstallDir)lib</ExcludePath> + </PropertyGroup> + <ItemDefinitionGroup> + <CustomBuild> + <Command>$(Masm) /Cx /Fo"$(SolutionDir)temp\$(Platform)\%(Filename).obj" /c "%(FullPath)"</Command> + <Message /> + <Outputs>$(SolutionDir)temp\$(Platform)\%(Filename).obj</Outputs> + </CustomBuild> + <ClCompile> + <Optimization Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Disabled</Optimization> + </ClCompile> + <ClCompile> + <FavorSizeOrSpeed Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">Neither</FavorSizeOrSpeed> + </ClCompile> + <ClCompile> + <OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</OmitFramePointers> + <StringPooling Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </StringPooling> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</MinimalRebuild> + <BasicRuntimeChecks Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">EnableFastChecks</BasicRuntimeChecks> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">MultiThreadedDLL</RuntimeLibrary> + <BufferSecurityCheck Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</BufferSecurityCheck> + <EnableFiberSafeOptimizations Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</EnableFiberSafeOptimizations> + <IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</IntrinsicFunctions> + <CreateHotpatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </CreateHotpatchableImage> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</MultiProcessorCompilation> + </ClCompile> + <Link> + <GenerateDebugInformation Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">true</GenerateDebugInformation> + <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">.\comserver.def</ModuleDefinitionFile> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </ImportLibrary> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</DataExecutionPrevention> + <CreateHotPatchableImage Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </CreateHotPatchableImage> + <HeapReserveSize Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </HeapReserveSize> + <Driver Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">NotSet</Driver> + <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </OptimizeReferences> + <LinkTimeCodeGeneration Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </LinkTimeCodeGeneration> + <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </EnableCOMDATFolding> + </Link> + <Link> + <ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'"> + </ImportLibrary> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> + </ImportLibrary> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> + </ImportLibrary> + <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</OptimizeReferences> + <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</OptimizeReferences> + <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</OptimizeReferences> + <OptimizeReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</OptimizeReferences> + <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</EnableCOMDATFolding> + <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</EnableCOMDATFolding> + <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</EnableCOMDATFolding> + <EnableCOMDATFolding Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</EnableCOMDATFolding> + <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <ForceSymbolReferences Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <AddModuleNamesToAssembly Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <AssemblyLinkResource Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</DataExecutionPrevention> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</DataExecutionPrevention> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</DataExecutionPrevention> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> + </IgnoreAllDefaultLibraries> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'"> + </IgnoreAllDefaultLibraries> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'"> + </IgnoreAllDefaultLibraries> + </Link> + <Midl> + <MkTypLibCompatible Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</MkTypLibCompatible> + </Midl> + <Link> + <ImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(TargetName).lib</ImportLibrary> + <ProgramDatabaseFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)$(TargetName).pdb</ProgramDatabaseFile> + </Link> + <Manifest> + <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + </OutputManifestFile> + <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + <RegistrarScriptFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + <ReplacementsFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" /> + </Manifest> + <Midl> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </Midl> + <Midl> + <MkTypLibCompatible Condition="'$(Configuration)'=='DebugDll' OR '$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDll(mbcs)'">true</MkTypLibCompatible> + <GenerateTypeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateTypeLibrary> + </Midl> + <ClCompile> + <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Use</PrecompiledHeader> + <ProgramDataBaseFileName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)</ProgramDataBaseFileName> + </ClCompile> + <Manifest> + <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <TypeLibraryFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> + <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'" /> + <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'" /> + <ComponentFileName Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'" /> + </Manifest> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">_DEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <ModuleDefinitionFile Condition="'$(Configuration)'=='ReleaseDll(mbcs)' OR '$(Configuration)'=='ReleaseDll'">.\comserver.def</ModuleDefinitionFile> + </Link> + <Link> + <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='Release|x64'" /> + <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'" /> + <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'" /> + <ModuleDefinitionFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">.\comserver.def</ModuleDefinitionFile> + </Link> + <Manifest> + <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'"> + </OutputManifestFile> + </Manifest> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'" /> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">_USRDLL;_DEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <Link> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</RandomizedBaseAddress> + </Link> + <Link> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</DataExecutionPrevention> + </Link> + <Link> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</RandomizedBaseAddress> + </Link> + <Link> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</DataExecutionPrevention> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'"> + </IgnoreAllDefaultLibraries> + </Link> + <Link> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</RandomizedBaseAddress> + </Link> + <Link> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</DataExecutionPrevention> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'"> + </IgnoreAllDefaultLibraries> + </Link> + <Link> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</RandomizedBaseAddress> + </Link> + <Link> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</DataExecutionPrevention> + </Link> + <Link> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</RandomizedBaseAddress> + </Link> + <Link> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</DataExecutionPrevention> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'"> + </IgnoreAllDefaultLibraries> + </Link> + <ClCompile> + <OmitFramePointers Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</OmitFramePointers> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreadedDLL</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</MultiProcessorCompilation> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MinimalRebuild> + </ClCompile> + <ProjectReference> + <UseLibraryDependencyInputs Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</UseLibraryDependencyInputs> + </ProjectReference> + <Bscmake> + <PreserveSBR Condition="'$(Configuration)|$(Platform)'=='DebugDll|Win32'">false</PreserveSBR> + </Bscmake> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">_WIN64;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">MultiThreadedDLL</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">false</MultiProcessorCompilation> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='DebugDll|x64'">true</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Release(minimal)|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(minimal)|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">false</MultiProcessorCompilation> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">MultiThreadedDLL</RuntimeLibrary> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|Win32'">true</MinimalRebuild> + </ClCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">false</MultiProcessorCompilation> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">MultiThreadedDLL</RuntimeLibrary> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|Win32'">true</MinimalRebuild> + </ClCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">false</MultiProcessorCompilation> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">MultiThreadedDLL</RuntimeLibrary> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Debug(mbcs)|x64'">true</MinimalRebuild> + </ClCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">false</MultiProcessorCompilation> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">MultiThreadedDLL</RuntimeLibrary> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(debug)|x64'">true</MinimalRebuild> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)'=='ReleaseDll' OR '$(Configuration)'=='ReleaseDll(mbcs)'"> + <Link> + <AdditionalDependencies>wsock32.lib;winmm.lib;version.lib;comctl32.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;psapi.lib;%(AdditionalDependencies)</AdditionalDependencies> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</DataExecutionPrevention> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</DataExecutionPrevention> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'"> + </IgnoreAllDefaultLibraries> + <IgnoreAllDefaultLibraries Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> + </IgnoreAllDefaultLibraries> + <RandomizedBaseAddress Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</RandomizedBaseAddress> + <DataExecutionPrevention Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</DataExecutionPrevention> + </Link> + <Manifest> + <OutputManifestFile Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'"> + </OutputManifestFile> + </Manifest> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">_USRDLL</PreprocessorDefinitions> + </ResourceCompile> + <ResourceCompile> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_USRDLL;_UNICODE;UNICODE;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">true</MultiProcessorCompilation> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">MultiThreaded</RuntimeLibrary> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">true</MultiProcessorCompilation> + <IntrinsicFunctions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</IntrinsicFunctions> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">MultiThreaded</RuntimeLibrary> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">false</MinimalRebuild> + </ClCompile> + <Midl> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">_WIN64</PreprocessorDefinitions> + </Midl> + <Midl> + <TargetEnvironment Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">X64</TargetEnvironment> + </Midl> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|Win32'">false</MinimalRebuild> + </ClCompile> + <ClCompile> + <RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">MultiThreaded</RuntimeLibrary> + <MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">true</MultiProcessorCompilation> + <TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">false</TreatWarningAsError> + <MinimalRebuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDll(mbcs)|x64'">false</MinimalRebuild> + </ClCompile> + </ItemDefinitionGroup> + <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> + <Link> + <ImportLibrary /> + <RandomizedBaseAddress>false</RandomizedBaseAddress> + <DataExecutionPrevention>false</DataExecutionPrevention> + </Link> + <ClCompile> + <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> + <MultiProcessorCompilation>false</MultiProcessorCompilation> + <MinimalRebuild>true</MinimalRebuild> + </ClCompile> + </ItemDefinitionGroup> + <ItemGroup> + <CustomBuild Include="source\lib\win2kcompat.asm"> + <ExcludedFromBuild Condition="'$(Platform)'!='Win32'">true</ExcludedFromBuild> + </CustomBuild> + <CustomBuild Include="source\libx64call\x64call.asm"> + <ExcludedFromBuild Condition="'$(Platform)'!='x64'">true</ExcludedFromBuild> + </CustomBuild> + <CustomBuild Include="source\libx64call\x64stub.asm"> + <ExcludedFromBuild Condition="'$(Platform)'!='x64'">true</ExcludedFromBuild> + </CustomBuild> + </ItemGroup> + <ItemGroup> + <ResourceCompile Include="source\resources\AutoHotkey.rc"> + <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|Win32'">_USRDLL;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions> + </ResourceCompile> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="source\lib_pcre\lib_pcre.vcxproj"> + <Project>{39037993-9571-4DF2-8E39-CD2909043574}</Project> + <ReferenceOutputAssembly>false</ReferenceOutputAssembly> + <Private>false</Private> + <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies> + <LinkLibraryDependencies>true</LinkLibraryDependencies> + <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <Manifest Include="source\resources\AutoHotkey.exe.manifest" /> + </ItemGroup> + <ItemGroup> + <None Include="ComServer.def"> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> + </None> + <None Include="source\resources\icon_filetype.ico" /> + <None Include="source\resources\icon_main.ico" /> + <None Include="source\resources\icon_pause.ico" /> + <None Include="source\resources\icon_pause_suspend.ico" /> + <None Include="source\resources\icon_suspend.ico" /> + <None Include="source\resources\icon_tray_win9x.ico" /> + <None Include="source\resources\icon_tray_win9x_suspend.ico" /> + </ItemGroup> + <ItemGroup> + <Midl Include="source\ComServer.idl"> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release(mbcs)|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='ReleaseDllMini(mbcs)|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained|Win32'">true</ExcludedFromBuild> + <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Self-contained(mbcs)|Win32'">true</ExcludedFromBuild> + <TargetEnvironment Condition="'$(Configuration)|$(Platform)'=='ReleaseDll|x64'">X64</TargetEnvironment> + </Midl> + </ItemGroup> + <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> </Project> \ No newline at end of file
tinku99/ahkdll
6b3c6265843f13f471c7dbbf73a4ae5c508bbf96
Fixed Alias not to resolve first parameter if it is alias
diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp index c09bc62..1dbb44b 100644 --- a/source/lowlevelbif.cpp +++ b/source/lowlevelbif.cpp @@ -1,128 +1,128 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" BIF_DECL(BIF_FindFunc) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } BIF_DECL(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00 { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname); aResultToken.value_int64 = (__int64)ahkFindLabel(labelname); return; } BIF_DECL(BIF_Getvar) { int i = 0; if (aParam[0]->symbol == SYM_VAR) i = (int)aParam[0]->var; aResultToken.value_int64 = i; } BIF_DECL(BIF_Static) { if (aParam[0]->symbol == SYM_VAR) { Var *var = aParam[0]->var; if (var->mType == VAR_ALIAS) var = var->mAliasFor; var->mAttrib |= VAR_LOCAL_STATIC; } } BIF_DECL(BIF_Alias) { ExprTokenType &aParam0 = *aParam[0]; ExprTokenType &aParam1 = *aParam[1]; if (aParam0.symbol == SYM_VAR) { - Var &var = (aParam[0]->var->mType == VAR_ALIAS ? *aParam0.var->ResolveAlias() : *aParam0.var); + Var &var = *aParam0.var; UINT_PTR len = 0; switch (aParam1.symbol) { case SYM_VAR: len = (UINT_PTR)(aParam[1]->var->mType == VAR_ALIAS ? aParam1.var->ResolveAlias() : aParam1.var); break; case SYM_INTEGER: // HotKeyIt added to accept var pointer len = (UINT_PTR)aParam[1]->value_int64; break; // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll case SYM_STRING: len = (UINT_PTR)ATOI64(aParam1.marker); } var.mType = len ? VAR_ALIAS : VAR_NORMAL; var.mByteLength = len; } } BIF_DECL(BIF_CacheEnable) { if (aParam[0]->symbol == SYM_VAR) { (aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var) ->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; } } BIF_DECL(BIF_getTokenValue) { ExprTokenType *token = aParam[0]; if (token->symbol != SYM_INTEGER) return; token = (ExprTokenType*) token->value_int64; if (token->symbol == SYM_VAR) { Var &var = *token->var; VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE); if (cache_attrib) { aResultToken.symbol = (SymbolType) (cache_attrib >> 4); aResultToken.value_int64 = var.mContentsInt64; } else if (var.mAttrib & VAR_ATTRIB_OBJECT) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = var.mObject; } else { aResultToken.symbol = SYM_OPERAND; aResultToken.marker = var.mCharContents; } } else { aResultToken.symbol = token->symbol; aResultToken.value_int64 = token->value_int64; } if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->AddRef(); } \ No newline at end of file
tinku99/ahkdll
9f5718bdc4197022bcf7bf9a770e7e0a2f597849
Fixed Alias to accept var ponter in secont parameter
diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp index f7195da..c09bc62 100644 --- a/source/lowlevelbif.cpp +++ b/source/lowlevelbif.cpp @@ -1,125 +1,128 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" BIF_DECL(BIF_FindFunc) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } BIF_DECL(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00 { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname); aResultToken.value_int64 = (__int64)ahkFindLabel(labelname); return; } BIF_DECL(BIF_Getvar) { int i = 0; if (aParam[0]->symbol == SYM_VAR) i = (int)aParam[0]->var; aResultToken.value_int64 = i; } BIF_DECL(BIF_Static) { if (aParam[0]->symbol == SYM_VAR) { Var *var = aParam[0]->var; if (var->mType == VAR_ALIAS) var = var->mAliasFor; var->mAttrib |= VAR_LOCAL_STATIC; } } BIF_DECL(BIF_Alias) { ExprTokenType &aParam0 = *aParam[0]; ExprTokenType &aParam1 = *aParam[1]; if (aParam0.symbol == SYM_VAR) { Var &var = (aParam[0]->var->mType == VAR_ALIAS ? *aParam0.var->ResolveAlias() : *aParam0.var); UINT_PTR len = 0; switch (aParam1.symbol) { case SYM_VAR: - case SYM_INTEGER: len = (UINT_PTR)(aParam[1]->var->mType == VAR_ALIAS ? aParam1.var->ResolveAlias() : aParam1.var); - break; - // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll - case SYM_OPERAND: + break; + case SYM_INTEGER: + // HotKeyIt added to accept var pointer + len = (UINT_PTR)aParam[1]->value_int64; + break; + // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll + case SYM_STRING: len = (UINT_PTR)ATOI64(aParam1.marker); } var.mType = len ? VAR_ALIAS : VAR_NORMAL; var.mByteLength = len; } } BIF_DECL(BIF_CacheEnable) { if (aParam[0]->symbol == SYM_VAR) { (aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var) ->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; } } BIF_DECL(BIF_getTokenValue) { ExprTokenType *token = aParam[0]; if (token->symbol != SYM_INTEGER) return; token = (ExprTokenType*) token->value_int64; if (token->symbol == SYM_VAR) { Var &var = *token->var; VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE); if (cache_attrib) { aResultToken.symbol = (SymbolType) (cache_attrib >> 4); aResultToken.value_int64 = var.mContentsInt64; } else if (var.mAttrib & VAR_ATTRIB_OBJECT) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = var.mObject; } else { aResultToken.symbol = SYM_OPERAND; aResultToken.marker = var.mCharContents; } } else { aResultToken.symbol = token->symbol; aResultToken.value_int64 = token->value_int64; } if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->AddRef(); } \ No newline at end of file
tinku99/ahkdll
b5876e2681b6bcb15abe1228e6661fe1da00c457
Fixed alignment to be max A_PtrSize
diff --git a/source/script_object_bif.cpp b/source/script_object_bif.cpp index fccfc28..8c0e6b9 100644 --- a/source/script_object_bif.cpp +++ b/source/script_object_bif.cpp @@ -1,697 +1,697 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "globaldata.h" #include "script.h" #include "script_object.h" // // BIF_Struct - Create structure // BIF_DECL(BIF_Struct) { // At least the definition for structure must be given if (!aParamCount) return; IObject *obj = Struct::Create(aParam,aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } // indicate error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_sizeof - sizeof() for structures and default types // BIF_DECL(BIF_sizeof) // This code is very similar to BIF_Struct so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[10]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int align = 0; int *aligntotal = &align; // pointer alignment for total structure int thissize; // used to save size returned from IsDefaultType // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; // used to pass aligntotal counter to structure in structure Var3.symbol = SYM_INTEGER; Var3.value_int64 = (__int64)&align; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; // will hold pointer to structure definition while we parse it TCHAR *buf; size_t buf_size; // Should be enough buffer to accept any definition and name. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; // Set result to empty string to identify error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; // if first parameter is an object (struct), simply return its size if (TokenToObject(*aParam[0])) { aResultToken.symbol = SYM_INTEGER; Struct *obj = (Struct*)TokenToObject(*aParam[0]); aResultToken.value_int64 = obj->mSize; return; } if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // an offset was given, set starting offset offset = (int)TokenToInt64(*aParam[1]); Var2.value_int64 = (__int64)offset; } if (aParamCount > 2 && TokenIsPureNumeric(*aParam[2])) { // a pointer was given to return memory to align aligntotal = (int *)TokenToInt64(*aParam[2],true); } // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // now restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { // end of structure, align it if (totalunionsize % *aligntotal) totalunionsize += *aligntotal - (totalunionsize % *aligntotal); if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; else if (offset % *aligntotal) offset += *aligntotal - (offset % *aligntotal); } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set default arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) return; _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) return; else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } // Pointer, while loop will continue here because we only need size if (_tcschr(tempbuf,'*')) { offset += ptrsize * (arraydef ? arraydef : 1); // align offset for pointer if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > *aligntotal) *aligntotal = ptrsize; // update offset if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now and continue if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); continue; } // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t ["))) > MAX_VAR_NAME_LENGTH*2 + 30) return; _tcsncpy(defbuf + 1,tempbuf,_tcscspn(tempbuf,_T("\t ["))); _tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t [")),_T(" ")); } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt _tcscpy(defbuf,_T(" UInt ")); // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; offset += thissize * (arraydef ? arraydef : 1); // align offset if (thissize > 1 && offset % thissize) { offset += thissize - (offset % thissize); } if (thissize > *aligntotal) - *aligntotal = thissize; + *aligntotal = thissize>ptrsize ? ptrsize : thissize; } else // type was not found, check for user defined type in variables { Var1.var = NULL; Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; return; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); if (Var1.var != NULL) { // Call BIF_sizeof passing offset in second parameter to align if necessary param[1]->value_int64 = (__int64)offset; BIF_sizeof(Result,ResultToken,param,3); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure return; } // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size, return empty string. return; } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); } if (*aligntotal && offset % *aligntotal) // align only if offset was not given offset += *aligntotal - (offset % *aligntotal); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = offset; } // // BIF_ObjCreate - Object() // BIF_DECL(BIF_ObjCreate) { IObject *obj = NULL; if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { if (obj = TokenToObject(*aParam[0])) { // Allow &obj == Object(obj), but AddRef() for equivalence with ComObjActive(comobj). obj->AddRef(); aResultToken.value_int64 = (__int64)obj; return; // symbol is already SYM_INTEGER. } obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = Object::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // BIF_ObjArray - Array(items*) // BIF_DECL(BIF_ObjArray) { Object *obj = Object::Create(); if (obj) { if (!aParamCount || obj->InsertAt(0, 1, aParam, aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; } obj->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_IsObject - IsObject(obj) // BIF_DECL(BIF_IsObject) // IsObject(obj) is currently equivalent to (obj && obj=""), but much more intuitive. { int i; for (i = 0; i < aParamCount && TokenToObject(*aParam[i]); ++i); aResultToken.value_int64 = (__int64)(i == aParamCount); // TRUE if all are objects. } // // BIF_ObjInvoke - Handles ObjGet/Set/Call() and get/set/call syntax. // BIF_DECL(BIF_ObjInvoke) { int invoke_type; IObject *obj; ExprTokenType *obj_param; // Since ObjGet/ObjSet/ObjCall are not publicly accessible as functions, Func::mName // (passed via aResultToken.marker) contains the actual flag rather than a name. invoke_type = (int)(INT_PTR)aResultToken.marker; // Set default return value; ONLY AFTER THE ABOVE. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); obj_param = *aParam; // aParam[0]. Load-time validation has ensured at least one parameter was specified. ++aParam; --aParamCount; // The following is used in place of TokenToObject to bypass #Warn UseUnset: if (obj_param->symbol == SYM_OBJECT) obj = obj_param->object; else if (obj_param->symbol == SYM_VAR && obj_param->var->HasObject()) obj = obj_param->var->Object(); else obj = NULL; if (obj) { bool param_is_var = obj_param->symbol == SYM_VAR; if (param_is_var) // Since the variable may be cleared as a side-effect of the invocation, call AddRef to ensure the object does not expire prematurely. // This is not necessary for SYM_OBJECT since that reference is already counted and cannot be released before we return. Each object // could take care not to delete itself prematurely, but it seems more proper, more reliable and more maintainable to handle it here. obj->AddRef(); aResult = obj->Invoke(aResultToken, *obj_param, invoke_type, aParam, aParamCount); if (param_is_var) obj->Release(); } // Invoke meta-functions of g_MetaObject. else if (INVOKE_NOT_HANDLED == (aResult = g_MetaObject.Invoke(aResultToken, *obj_param, invoke_type | IF_META, aParam, aParamCount))) { // Since above did not handle it, check for attempts to access .base of non-object value (g_MetaObject itself). if ( invoke_type != IT_CALL // Exclude things like "".base(). && aParamCount > (invoke_type == IT_SET ? 2 : 0) // SET is supported only when an index is specified: "".base[x]:=y && !_tcsicmp(TokenToString(*aParam[0]), _T("base")) ) { if (aParamCount > 1) // "".base[x] or similar { // Re-invoke g_MetaObject without meta flag or "base" param. ExprTokenType base_token; base_token.symbol = SYM_OBJECT; base_token.object = &g_MetaObject; g_MetaObject.Invoke(aResultToken, base_token, invoke_type, aParam + 1, aParamCount - 1); } else // "".base { // Return a reference to g_MetaObject. No need to AddRef as g_MetaObject ignores it. aResultToken.symbol = SYM_OBJECT; aResultToken.object = &g_MetaObject; } } else { // Since it wasn't handled (not even by g_MetaObject), maybe warn at this point: if (obj_param->symbol == SYM_VAR) obj_param->var->MaybeWarnUninitialized(); } } if (aResult == INVOKE_NOT_HANDLED) aResult = OK; } // // BIF_ObjGetInPlace - Handles part of a compound assignment like x.y += z. // BIF_DECL(BIF_ObjGetInPlace) { // Since the most common cases have two params, the "param count" param is omitted in // those cases. Otherwise we have one visible parameter, which indicates the number of // actual parameters below it on the stack. aParamCount = aParamCount ? (int)TokenToInt64(*aParam[0]) : 2; // x[<n-1 params>] : x.y BIF_ObjInvoke(aResult, aResultToken, aParam - aParamCount, aParamCount); } // // BIF_ObjNew - Handles "new" as in "new Class()". // BIF_DECL(BIF_ObjNew) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ExprTokenType *class_token = aParam[0]; // Save this to be restored later. IObject *class_object = TokenToObject(*class_token); if (!class_object) return; Object *new_object = Object::Create(); if (!new_object) return; new_object->SetBase(class_object); ExprTokenType name_token, this_token; this_token.symbol = SYM_OBJECT; this_token.object = new_object; name_token.symbol = SYM_STRING; aParam[0] = &name_token; ResultType result; LPTSTR buf = aResultToken.buf; // In case Invoke overwrites it via the union. // __Init was added so that instance variables can be initialized in the correct order // (beginning at the root class and ending at class_object) before __New is called. // It shouldn't be explicitly defined by the user, but auto-generated in DefineClassVars(). name_token.marker = _T("__Init"); result = class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, 1); if (result != INVOKE_NOT_HANDLED) { // See similar section below for comments. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Reset to defaults for __New, invoked below. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); aResultToken.buf = buf; if (result == FAIL) { aParam[0] = class_token; // Restore it to original caller-supplied value. return; } } // __New may be defined by the script for custom initialization code. name_token.marker = Object::sMetaFuncName[4]; // __New if (class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, aParamCount) != EARLY_RETURN) { // Although it isn't likely to happen, if __New points at a built-in function or if mBase // (or an ancestor) is not an Object (i.e. it's a ComObject), aResultToken can be set even when // the result is not EARLY_RETURN. So make sure to clean up any result we're not going to use. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { // This can be done by our caller, but is done here for maintainability; i.e. because // some callers might expect mem_to_free to be NULL when the result isn't a string. free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Either it wasn't handled (i.e. neither this class nor any of its super-classes define __New()), // or there was no explicit "return", so just return the new object. aResultToken.symbol = SYM_OBJECT; aResultToken.object = this_token.object; } else new_object->Release(); aParam[0] = class_token; } // // BIF_ObjIncDec - Handles pre/post-increment/decrement for object fields, such as ++x[y]. // BIF_DECL(BIF_ObjIncDec) { // Func::mName (which aResultToken.marker is set to) has been overloaded to pass // the type of increment/decrement to be performed on this object's field. SymbolType op = (SymbolType)(INT_PTR)aResultToken.marker; ExprTokenType temp_result, current_value, value_to_set; // Set the defaults expected by BIF_ObjInvoke: temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_GET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Retrieve the current value. Do it this way instead of calling Object::Invoke // so that if aParam[0] is not an object, g_MetaObject is correctly invoked. BIF_ObjInvoke(aResult, temp_result, aParam, aParamCount); if (aResult == FAIL || aResult == EARLY_EXIT) return; // Change SYM_STRING to SYM_OPERAND so below may treat it as a numeric string. if (temp_result.symbol == SYM_STRING) { temp_result.symbol = SYM_OPERAND; temp_result.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } switch (value_to_set.symbol = current_value.symbol = TokenIsPureNumeric(temp_result)) { case PURE_INTEGER: value_to_set.value_int64 = (current_value.value_int64 = TokenToInt64(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; case PURE_FLOAT: value_to_set.value_double = (current_value.value_double = TokenToDouble(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; } // Free the object or string returned by BIF_ObjInvoke, if applicable. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); if (current_value.symbol == PURE_NOT_NUMERIC) { // Value is non-numeric, so assign and return "". value_to_set.symbol = SYM_STRING; value_to_set.marker = _T(""); //current_value.symbol = SYM_STRING; // Already done (SYM_STRING == PURE_NOT_NUMERIC). current_value.marker = _T(""); } // Although it's likely our caller's param array has enough space to hold the extra // parameter, there's no way to know for sure whether it's safe, so we allocate our own: ExprTokenType **param = (ExprTokenType **)_alloca((aParamCount + 1) * sizeof(ExprTokenType *)); memcpy(param, aParam, aParamCount * sizeof(ExprTokenType *)); // Copy caller's param pointers. param[aParamCount++] = &value_to_set; // Append new value as the last parameter. if (op == SYM_PRE_INCREMENT || op == SYM_PRE_DECREMENT) { aResultToken.marker = (LPTSTR)IT_SET; // Set the new value and pass the return value of the invocation back to our caller. // This should be consistent with something like x.y := x.y + 1. BIF_ObjInvoke(aResult, aResultToken, param, aParamCount); } else // SYM_POST_INCREMENT || SYM_POST_DECREMENT { // Must be re-initialized (and must use IT_SET instead of IT_GET): temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_SET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Set the new value. BIF_ObjInvoke(aResult, temp_result, param, aParamCount); // Dispose of the result safely. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); // Return the previous value. aResultToken.symbol = current_value.symbol; aResultToken.value_int64 = current_value.value_int64; // Union copy. } } // // Functions for accessing built-in methods (even if obscured by a user-defined method). // #define BIF_METHOD(name) \ BIF_DECL(BIF_Obj##name) \ { \ aResultToken.symbol = SYM_STRING; \ aResultToken.marker = _T(""); \ \ Object *obj = dynamic_cast<Object*>(TokenToObject(*aParam[0])); \ if (obj) \ obj->_##name(aResultToken, aParam + 1, aParamCount - 1); \ } BIF_METHOD(Insert) BIF_METHOD(Remove) BIF_METHOD(GetCapacity) BIF_METHOD(SetCapacity) BIF_METHOD(GetAddress) BIF_METHOD(MaxIndex) BIF_METHOD(MinIndex) BIF_METHOD(NewEnum) BIF_METHOD(HasKey) BIF_METHOD(Clone) // // ObjAddRef/ObjRelease - used with pointers rather than object references. // BIF_DECL(BIF_ObjAddRefRelease) { IObject *obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)4096) // Rule out some obvious errors. { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[3]) == 'A') aResultToken.value_int64 = obj->AddRef(); else aResultToken.value_int64 = obj->Release(); } \ No newline at end of file diff --git a/source/script_struct.cpp b/source/script_struct.cpp index bfd7535..9776533 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -1,763 +1,763 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "application.h" #include "globaldata.h" #include "script.h" #include "TextIO.h" #include "script_object.h" // // Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set. // Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount) // This code is very similar to BIF_sizeof so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[100]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int ispointer = NULL; // identify pointer and how deep it goes int aligntotal = 0; // pointer alignment for total structure int thissize; // used to check if type was found in above array. // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; Var3.symbol = SYM_INTEGER; // will hold pointer to structure definition string while we parse trough it TCHAR *buf; size_t buf_size; // Use enough buffer to accept any definition in a field. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable) TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; FieldType *field; // used to define a field // Structure object is saved in fixed order // insert_pos is simply increased each time // for loop will enumerate items in same order as it was created IndexType insert_pos = 0; // the new structure object Struct *obj = new Struct(); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; if (TokenToObject(*aParam[0])) { obj->Release(); obj = ((Struct *)TokenToObject(*aParam[0]))->Clone(); if (aParamCount > 2) { obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); obj->ObjectToStruct(TokenToObject(*aParam[2])); } else if (aParamCount > 1) { if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,offset); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); } else { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); } return obj; } // Set initial capacity to avoid multiple expansions. // For simplicity, failure is handled by the loop below. obj->SetInternalCapacity(aParamCount >> 1); // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; // backup offset unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { // end of structure, align it if (totalunionsize % aligntotal) totalunionsize += aligntotal - (totalunionsize % aligntotal); if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; else if (offset % aligntotal) offset += aligntotal - (offset % aligntotal); } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set defaults ispointer = false; arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) { obj->Release(); return NULL; } _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) { obj->Release(); return NULL; } else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Pointer if (_tcschr(tempbuf,'*')) ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition from temp buffer to identify key easier StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Trim trailing spaces in case we had a definition like UInt [10] rtrim(tempbuf); } // copy type // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30) { obj->Release(); return NULL; } _tcsncpy(defbuf + 1,tempbuf,buf_size); //_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" ")); defbuf[1 + buf_size] = ' '; defbuf[2 + buf_size] = '\0'; if (StrChrAny(tempbuf, _T(" \t"))) { if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30) { obj->Release(); return NULL; } _tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1); ltrim(keybuf); } else keybuf[0] = '\0'; } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt { _tcscpy(defbuf,_T(" UInt ")); _tcscpy(keybuf,tempbuf); } // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; // align offset if (ispointer) { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } else { if (offset % thissize) offset += thissize - (offset % thissize); if (thissize > aligntotal) - aligntotal = thissize; + aligntotal = thissize > ptrsize ? ptrsize : thissize; } if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) { // Out of memory. obj->Release(); return NULL; } offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); } else // type was not found, check for user defined type in variables { Var1.var = NULL; // init to not found Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("*MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; obj->Release(); return NULL; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); // variable found if (Var1.var != NULL) { if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf) { // Whole definition is not a pointer and no key was given so create Structure from variable obj->Release(); if (aParamCount == 1) { if (TokenToObject(*param[0])) { // assume variable is a structure object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); return obj; } // else create structure from string definition return Struct::Create(param,1); } else if (aParamCount > 1) { // more than one parameter was given, copy aParam to param param[1]->symbol = aParam[1]->symbol; param[1]->object = aParam[1]->object; param[1]->value_int64 = aParam[1]->value_int64; param[1]->var = aParam[1]->var; } if (aParamCount > 2) { // more than 2 parameters were given, copy aParam to param param[2]->symbol = aParam[2]->symbol; param[2]->object = aParam[2]->object; param[2]->var = aParam[2]->var; // definition variable is a structure object, clone it, assign memory and init object if (TokenToObject(*param[0])) { obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mMemAllocated = 0; obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; obj->ObjectToStruct(TokenToObject(*aParam[2])); return obj; } return Struct::Create(param,3); } else if (TokenToObject(*param[0])) { // definition variable is a structure object, clone it and assign memory or init object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; return obj; } // else simply create structure from variable and given memory/initobject return Struct::Create(param,2); } // Call BIF_sizeof passing offset in second parameter to align offset if necessary // if field is a pointer we will need its size only if (!ispointer) { param[1]->value_int64 = (__int64)ispointer ? 0 : offset; param[2]->value_int64 = (__int64)&aligntotal; BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure obj->Release(); return NULL; } } else { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } // Insert new field in our structure if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? ptrsize : (int)ResultToken.value_int64,1,1,-1))) { // Out of memory. obj->Release(); return NULL; } if (ispointer) offset += (int)ptrsize * (arraydef ? arraydef : 1); else // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size. { obj->Release(); return NULL; } } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else { // identify that structure object has no fields if (!*keybuf) obj->mTypeOnly = true; buf += _tcslen(buf); } } // align total structure if necessary if (aligntotal && offset % aligntotal) offset += aligntotal - (offset % aligntotal); if (!offset) // structure could not be build { obj->Release(); return NULL; } obj->mSize = offset; if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // second parameter exist and it is digit assumme this is new pointer for our structure obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]); obj->mMemAllocated = 0; } else // no pointer given so allocate memory and fill memory with 0 { // setting the memory after parsing definition saves a call to BIF_sizeof obj->mStructMem = (UINT_PTR *)malloc(offset); obj->mMemAllocated = offset; memset(obj->mStructMem,NULL,offset); } // an object was passed to initialize fields // enumerate trough object and assign values if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 ) obj->ObjectToStruct(TokenToObject(aParamCount == 2 ? *aParam[1] : *aParam[2])); return obj; } // // Struct::ObjectToStruct - Initialize structure from array, object or structure. // void Struct::ObjectToStruct(IObject *objfrom) { ExprTokenType ResultToken, this_token,enum_token,param_tokens[3]; ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 }; TCHAR defbuf[MAX_PATH],buf[MAX_PATH]; int param_count = 3; // Set up enum_token the way Invoke expects: enum_token.symbol = SYM_STRING; enum_token.marker = _T(""); enum_token.mem_to_free = NULL; enum_token.buf = defbuf; // Prepare to call object._NewEnum(): param_tokens[0].symbol = SYM_STRING; param_tokens[0].marker = _T("_NewEnum"); objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1); if (enum_token.mem_to_free) // Invoke returned memory for us to free. free(enum_token.mem_to_free); // Check if object returned an enumerator, otherwise return if (enum_token.symbol != SYM_OBJECT) return; // create variables to use in for loop / for enumeration // these will be deleted afterwards Var *var1 = (Var*)alloca(sizeof(Var)); Var *var2 = (Var*)alloca(sizeof(Var)); var1->mType = var2->mType = VAR_NORMAL; var1->mAttrib = var2->mAttrib = 0; var1->mByteCapacity = var2->mByteCapacity = 0; var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC; // Prepare parameters for the loop below: enum.Next(var1 [, var2]) param_tokens[0].marker = _T("Next"); param_tokens[1].symbol = SYM_VAR; param_tokens[1].var = var1; param_tokens[1].mem_to_free = 0; param_tokens[2].symbol = SYM_VAR; param_tokens[2].var = var2; param_tokens[2].mem_to_free = 0; ExprTokenType result_token; IObject &enumerator = *enum_token.object; // Might perform better as a reference? this_token.symbol = SYM_OBJECT; this_token.object = this; for (;;) { // Set up result_token the way Invoke expects; each Invoke() will change some or all of these: result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; // Call enumerator.Next(var1, var2) enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count); bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token)); if (!next_returned_true) break; this->Invoke(ResultToken,this_token,IT_SET,params+1,2); // release object if it was assigned prevoiously when calling enum.Next if (var1->IsObject()) var1->ReleaseObject(); if (var2->IsObject()) var2->ReleaseObject(); // Free any memory or object which may have been returned by Invoke: if (result_token.mem_to_free) free(result_token.mem_to_free); if (result_token.symbol == SYM_OBJECT) result_token.object->Release(); } // release enumerator and free vars enumerator.Release(); var1->Free(); var2->Free(); } // // Struct::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool Struct::Delete() { return ObjectBase::Delete(); } Struct::~Struct() { if (mMemAllocated > 0) free(mStructMem); if (mFields) { if (mFieldCount) { IndexType i = mFieldCount - 1; // Free keys for ( ; i >= 0 ; --i) { if (mFields[i].mMemAllocated > 0) free(mFields[i].mStructMem); free(mFields[i].key); } } // Free fields array. free(mFields); } } // // Struct::SetPointer - used to set pointer for a field or array item // UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem) { if (mIsPointer) *((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; else *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; return aPointer; } // // Struct::FieldType::Clone - used to clone a field to structure. // Struct *Struct::CloneField(FieldType *field,bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; // if field is an array, set correct size if (obj.mArraySize = field->mArraySize) obj.mSize = field->mSize*obj.mArraySize; else obj.mSize = field->mSize; obj.mIsInteger = field->mIsInteger; obj.mIsPointer = field->mIsPointer; obj.mEncoding = field->mEncoding; obj.mIsUnsigned = field->mIsUnsigned; obj.mVarRef = field->mVarRef; obj.mTypeOnly = 1; obj.mMemAllocated = aIsDynamic ? -1 : 0; return objptr; } // // Struct::Clone - used for cloning structures. // Struct *Struct::Clone(bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; obj.mArraySize = mArraySize; obj.mIsInteger = mIsInteger; obj.mIsPointer = mIsPointer; obj.mEncoding = mEncoding; obj.mIsUnsigned = mIsUnsigned; obj.mSize = mSize; obj.mVarRef = mVarRef; obj.mTypeOnly = mTypeOnly; // -1 will identify a dynamic structure, no memory can be allocated to such obj.mMemAllocated = aIsDynamic ? -1 : 0; // Allocate space in destination object. if (!obj.SetInternalCapacity(mFieldCount)) { obj.Release(); return NULL; } FieldType *fields = obj.mFields; // Newly allocated by above. int failure_count = 0; // See comment below. IndexType i; obj.mFieldCount = mFieldCount; for (i = 0; i < mFieldCount; ++i) { FieldType &dst = fields[i]; FieldType &src = mFields[i]; if ( !(dst.key = _tcsdup(src.key)) ) { // Key allocation failed. // Rather than trying to set up the object so that what we have // so far is valid in order to break out of the loop, continue, // make all fields valid and then allow them to be freed. ++failure_count; } dst.mArraySize = src.mArraySize; dst.mIsInteger = src.mIsInteger; dst.mIsPointer = src.mIsPointer; dst.mEncoding = src.mEncoding; dst.mIsUnsigned = src.mIsUnsigned; dst.mOffset = src.mOffset; dst.mSize = src.mSize; dst.mVarRef = src.mVarRef; dst.mMemAllocated = aIsDynamic ? -1 : 0; } if (failure_count) { // One or more memory allocations failed. It seems best to return a clear failure // indication rather than an incomplete copy. Now that the loop above has finished, // the object's contents are at least valid and it is safe to free the object: obj.Release(); return NULL; } return &obj; } // // Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object. // ResultType STDMETHODCALLTYPE Struct::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) // L40: Revised base mechanism for flexibility and to simplify some aspects. // obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc. { int ptrsize = sizeof(UINT_PTR); FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL ResultType Result = OK; // Used to resolve dynamic structures ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2},ResultToken; // used to clone a dynamic field or structure Struct *objclone = NULL; // used for StrGet/StrPut LPCVOID source_string; int source_length; DWORD flags = WC_NO_BEST_FIT_CHARS; int length = -1; int char_count; // Identify that we need to release/delete field or structure object bool deletefield = false; bool releaseobj = false; int param_count_excluding_rvalue = aParamCount; // target may be altered here to resolve dynamic structure so hold it separately UINT_PTR *target = mStructMem; if (IS_INVOKE_SET) { // Prior validation of ObjSet() param count ensures the result won't be negative: --param_count_excluding_rvalue; // Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best // to have it also block __Set. The code below is disabled to achieve this, with a slight cost to // performance when assigning to a new key in any object which has a base object. (The cost may // depend on how many key-value pairs each base object has.) Note that this doesn't affect meta- // functions defined in *this* base object, since they were already invoked if present. //if (IS_INVOKE_META) //{ // if (param_count_excluding_rvalue == 1) // // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to. // // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue. // param_count_excluding_rvalue = 0; // //else: Allow SET to operate on a field of an object stored in the target's base. // // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc. //} } if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0]))) { // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr if (IS_INVOKE_SET) { if (TokenToObject(*aParam[param_count_excluding_rvalue])) { // Initialize structure using an object. e.g. struct[]:={x:1,y:2} this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue])); // return struct object aResultToken.symbol = SYM_OBJECT; aResultToken.object = this; this->AddRef(); return OK; } if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer { free(mStructMem); mMemAllocated = 0; }
tinku99/ahkdll
2fbdf5a11b49960a5bb6d522e9d110fe76b3f77e
Fixed alignment for strurctures in structures, also sizeof() returns correct size now
diff --git a/source/script_object_bif.cpp b/source/script_object_bif.cpp index ef21bb8..fccfc28 100644 --- a/source/script_object_bif.cpp +++ b/source/script_object_bif.cpp @@ -1,684 +1,697 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "globaldata.h" #include "script.h" #include "script_object.h" // // BIF_Struct - Create structure // BIF_DECL(BIF_Struct) { // At least the definition for structure must be given if (!aParamCount) return; IObject *obj = Struct::Create(aParam,aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } // indicate error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_sizeof - sizeof() for structures and default types // BIF_DECL(BIF_sizeof) // This code is very similar to BIF_Struct so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[10]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure - int aligntotal = 0; // pointer alignment for total structure + int align = 0; + int *aligntotal = &align; // pointer alignment for total structure int thissize; // used to save size returned from IsDefaultType // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; - ExprTokenType Var1,Var2; + ExprTokenType Var1,Var2,Var3; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; - ExprTokenType *param[] = {&Var1,&Var2}; + + // used to pass aligntotal counter to structure in structure + Var3.symbol = SYM_INTEGER; + Var3.value_int64 = (__int64)&align; + ExprTokenType *param[] = {&Var1,&Var2,&Var3}; // will hold pointer to structure definition while we parse it TCHAR *buf; size_t buf_size; // Should be enough buffer to accept any definition and name. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; // Set result to empty string to identify error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; // if first parameter is an object (struct), simply return its size if (TokenToObject(*aParam[0])) { aResultToken.symbol = SYM_INTEGER; Struct *obj = (Struct*)TokenToObject(*aParam[0]); aResultToken.value_int64 = obj->mSize; return; } if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // an offset was given, set starting offset offset = (int)TokenToInt64(*aParam[1]); Var2.value_int64 = (__int64)offset; } - + if (aParamCount > 2 && TokenIsPureNumeric(*aParam[2])) + { // a pointer was given to return memory to align + aligntotal = (int *)TokenToInt64(*aParam[2],true); + } // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // now restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { + // end of structure, align it + if (totalunionsize % *aligntotal) + totalunionsize += *aligntotal - (totalunionsize % *aligntotal); if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; + else if (offset % *aligntotal) + offset += *aligntotal - (offset % *aligntotal); } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set default arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) return; _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) return; else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } // Pointer, while loop will continue here because we only need size if (_tcschr(tempbuf,'*')) { offset += ptrsize * (arraydef ? arraydef : 1); // align offset for pointer if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); - if (ptrsize > aligntotal) - aligntotal = ptrsize; + if (ptrsize > *aligntotal) + *aligntotal = ptrsize; // update offset if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now and continue if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); continue; } // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t ["))) > MAX_VAR_NAME_LENGTH*2 + 30) return; _tcsncpy(defbuf + 1,tempbuf,_tcscspn(tempbuf,_T("\t ["))); _tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t [")),_T(" ")); } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt _tcscpy(defbuf,_T(" UInt ")); // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; offset += thissize * (arraydef ? arraydef : 1); // align offset if (thissize > 1 && offset % thissize) { offset += thissize - (offset % thissize); - if (thissize > aligntotal) - aligntotal = thissize; } + if (thissize > *aligntotal) + *aligntotal = thissize; } else // type was not found, check for user defined type in variables { Var1.var = NULL; Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; return; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); if (Var1.var != NULL) { // Call BIF_sizeof passing offset in second parameter to align if necessary param[1]->value_int64 = (__int64)offset; - BIF_sizeof(Result,ResultToken,param,2); + BIF_sizeof(Result,ResultToken,param,3); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure return; } // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size, return empty string. return; } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); } - if (aligntotal && offset % aligntotal) // align only if offset was not given - offset += aligntotal - (offset % aligntotal); + if (*aligntotal && offset % *aligntotal) // align only if offset was not given + offset += *aligntotal - (offset % *aligntotal); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = offset; } // // BIF_ObjCreate - Object() // BIF_DECL(BIF_ObjCreate) { IObject *obj = NULL; if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { if (obj = TokenToObject(*aParam[0])) { // Allow &obj == Object(obj), but AddRef() for equivalence with ComObjActive(comobj). obj->AddRef(); aResultToken.value_int64 = (__int64)obj; return; // symbol is already SYM_INTEGER. } obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = Object::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // BIF_ObjArray - Array(items*) // BIF_DECL(BIF_ObjArray) { Object *obj = Object::Create(); if (obj) { if (!aParamCount || obj->InsertAt(0, 1, aParam, aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; } obj->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_IsObject - IsObject(obj) // BIF_DECL(BIF_IsObject) // IsObject(obj) is currently equivalent to (obj && obj=""), but much more intuitive. { int i; for (i = 0; i < aParamCount && TokenToObject(*aParam[i]); ++i); aResultToken.value_int64 = (__int64)(i == aParamCount); // TRUE if all are objects. } // // BIF_ObjInvoke - Handles ObjGet/Set/Call() and get/set/call syntax. // BIF_DECL(BIF_ObjInvoke) { int invoke_type; IObject *obj; ExprTokenType *obj_param; // Since ObjGet/ObjSet/ObjCall are not publicly accessible as functions, Func::mName // (passed via aResultToken.marker) contains the actual flag rather than a name. invoke_type = (int)(INT_PTR)aResultToken.marker; // Set default return value; ONLY AFTER THE ABOVE. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); obj_param = *aParam; // aParam[0]. Load-time validation has ensured at least one parameter was specified. ++aParam; --aParamCount; // The following is used in place of TokenToObject to bypass #Warn UseUnset: if (obj_param->symbol == SYM_OBJECT) obj = obj_param->object; else if (obj_param->symbol == SYM_VAR && obj_param->var->HasObject()) obj = obj_param->var->Object(); else obj = NULL; if (obj) { bool param_is_var = obj_param->symbol == SYM_VAR; if (param_is_var) // Since the variable may be cleared as a side-effect of the invocation, call AddRef to ensure the object does not expire prematurely. // This is not necessary for SYM_OBJECT since that reference is already counted and cannot be released before we return. Each object // could take care not to delete itself prematurely, but it seems more proper, more reliable and more maintainable to handle it here. obj->AddRef(); aResult = obj->Invoke(aResultToken, *obj_param, invoke_type, aParam, aParamCount); if (param_is_var) obj->Release(); } // Invoke meta-functions of g_MetaObject. else if (INVOKE_NOT_HANDLED == (aResult = g_MetaObject.Invoke(aResultToken, *obj_param, invoke_type | IF_META, aParam, aParamCount))) { // Since above did not handle it, check for attempts to access .base of non-object value (g_MetaObject itself). if ( invoke_type != IT_CALL // Exclude things like "".base(). && aParamCount > (invoke_type == IT_SET ? 2 : 0) // SET is supported only when an index is specified: "".base[x]:=y && !_tcsicmp(TokenToString(*aParam[0]), _T("base")) ) { if (aParamCount > 1) // "".base[x] or similar { // Re-invoke g_MetaObject without meta flag or "base" param. ExprTokenType base_token; base_token.symbol = SYM_OBJECT; base_token.object = &g_MetaObject; g_MetaObject.Invoke(aResultToken, base_token, invoke_type, aParam + 1, aParamCount - 1); } else // "".base { // Return a reference to g_MetaObject. No need to AddRef as g_MetaObject ignores it. aResultToken.symbol = SYM_OBJECT; aResultToken.object = &g_MetaObject; } } else { // Since it wasn't handled (not even by g_MetaObject), maybe warn at this point: if (obj_param->symbol == SYM_VAR) obj_param->var->MaybeWarnUninitialized(); } } if (aResult == INVOKE_NOT_HANDLED) aResult = OK; } // // BIF_ObjGetInPlace - Handles part of a compound assignment like x.y += z. // BIF_DECL(BIF_ObjGetInPlace) { // Since the most common cases have two params, the "param count" param is omitted in // those cases. Otherwise we have one visible parameter, which indicates the number of // actual parameters below it on the stack. aParamCount = aParamCount ? (int)TokenToInt64(*aParam[0]) : 2; // x[<n-1 params>] : x.y BIF_ObjInvoke(aResult, aResultToken, aParam - aParamCount, aParamCount); } // // BIF_ObjNew - Handles "new" as in "new Class()". // BIF_DECL(BIF_ObjNew) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ExprTokenType *class_token = aParam[0]; // Save this to be restored later. IObject *class_object = TokenToObject(*class_token); if (!class_object) return; Object *new_object = Object::Create(); if (!new_object) return; new_object->SetBase(class_object); ExprTokenType name_token, this_token; this_token.symbol = SYM_OBJECT; this_token.object = new_object; name_token.symbol = SYM_STRING; aParam[0] = &name_token; ResultType result; LPTSTR buf = aResultToken.buf; // In case Invoke overwrites it via the union. // __Init was added so that instance variables can be initialized in the correct order // (beginning at the root class and ending at class_object) before __New is called. // It shouldn't be explicitly defined by the user, but auto-generated in DefineClassVars(). name_token.marker = _T("__Init"); result = class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, 1); if (result != INVOKE_NOT_HANDLED) { // See similar section below for comments. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Reset to defaults for __New, invoked below. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); aResultToken.buf = buf; if (result == FAIL) { aParam[0] = class_token; // Restore it to original caller-supplied value. return; } } // __New may be defined by the script for custom initialization code. name_token.marker = Object::sMetaFuncName[4]; // __New if (class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, aParamCount) != EARLY_RETURN) { // Although it isn't likely to happen, if __New points at a built-in function or if mBase // (or an ancestor) is not an Object (i.e. it's a ComObject), aResultToken can be set even when // the result is not EARLY_RETURN. So make sure to clean up any result we're not going to use. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { // This can be done by our caller, but is done here for maintainability; i.e. because // some callers might expect mem_to_free to be NULL when the result isn't a string. free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Either it wasn't handled (i.e. neither this class nor any of its super-classes define __New()), // or there was no explicit "return", so just return the new object. aResultToken.symbol = SYM_OBJECT; aResultToken.object = this_token.object; } else new_object->Release(); aParam[0] = class_token; } // // BIF_ObjIncDec - Handles pre/post-increment/decrement for object fields, such as ++x[y]. // BIF_DECL(BIF_ObjIncDec) { // Func::mName (which aResultToken.marker is set to) has been overloaded to pass // the type of increment/decrement to be performed on this object's field. SymbolType op = (SymbolType)(INT_PTR)aResultToken.marker; ExprTokenType temp_result, current_value, value_to_set; // Set the defaults expected by BIF_ObjInvoke: temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_GET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Retrieve the current value. Do it this way instead of calling Object::Invoke // so that if aParam[0] is not an object, g_MetaObject is correctly invoked. BIF_ObjInvoke(aResult, temp_result, aParam, aParamCount); if (aResult == FAIL || aResult == EARLY_EXIT) return; // Change SYM_STRING to SYM_OPERAND so below may treat it as a numeric string. if (temp_result.symbol == SYM_STRING) { temp_result.symbol = SYM_OPERAND; temp_result.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } switch (value_to_set.symbol = current_value.symbol = TokenIsPureNumeric(temp_result)) { case PURE_INTEGER: value_to_set.value_int64 = (current_value.value_int64 = TokenToInt64(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; case PURE_FLOAT: value_to_set.value_double = (current_value.value_double = TokenToDouble(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; } // Free the object or string returned by BIF_ObjInvoke, if applicable. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); if (current_value.symbol == PURE_NOT_NUMERIC) { // Value is non-numeric, so assign and return "". value_to_set.symbol = SYM_STRING; value_to_set.marker = _T(""); //current_value.symbol = SYM_STRING; // Already done (SYM_STRING == PURE_NOT_NUMERIC). current_value.marker = _T(""); } // Although it's likely our caller's param array has enough space to hold the extra // parameter, there's no way to know for sure whether it's safe, so we allocate our own: ExprTokenType **param = (ExprTokenType **)_alloca((aParamCount + 1) * sizeof(ExprTokenType *)); memcpy(param, aParam, aParamCount * sizeof(ExprTokenType *)); // Copy caller's param pointers. param[aParamCount++] = &value_to_set; // Append new value as the last parameter. if (op == SYM_PRE_INCREMENT || op == SYM_PRE_DECREMENT) { aResultToken.marker = (LPTSTR)IT_SET; // Set the new value and pass the return value of the invocation back to our caller. // This should be consistent with something like x.y := x.y + 1. BIF_ObjInvoke(aResult, aResultToken, param, aParamCount); } else // SYM_POST_INCREMENT || SYM_POST_DECREMENT { // Must be re-initialized (and must use IT_SET instead of IT_GET): temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_SET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Set the new value. BIF_ObjInvoke(aResult, temp_result, param, aParamCount); // Dispose of the result safely. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); // Return the previous value. aResultToken.symbol = current_value.symbol; aResultToken.value_int64 = current_value.value_int64; // Union copy. } } // // Functions for accessing built-in methods (even if obscured by a user-defined method). // #define BIF_METHOD(name) \ BIF_DECL(BIF_Obj##name) \ { \ aResultToken.symbol = SYM_STRING; \ aResultToken.marker = _T(""); \ \ Object *obj = dynamic_cast<Object*>(TokenToObject(*aParam[0])); \ if (obj) \ obj->_##name(aResultToken, aParam + 1, aParamCount - 1); \ } BIF_METHOD(Insert) BIF_METHOD(Remove) BIF_METHOD(GetCapacity) BIF_METHOD(SetCapacity) BIF_METHOD(GetAddress) BIF_METHOD(MaxIndex) BIF_METHOD(MinIndex) BIF_METHOD(NewEnum) BIF_METHOD(HasKey) BIF_METHOD(Clone) // // ObjAddRef/ObjRelease - used with pointers rather than object references. // BIF_DECL(BIF_ObjAddRefRelease) { IObject *obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)4096) // Rule out some obvious errors. { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[3]) == 'A') aResultToken.value_int64 = obj->AddRef(); else aResultToken.value_int64 = obj->Release(); } \ No newline at end of file diff --git a/source/script_struct.cpp b/source/script_struct.cpp index 318b9c6..bfd7535 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -1,863 +1,870 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "application.h" #include "globaldata.h" #include "script.h" #include "TextIO.h" #include "script_object.h" // // Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set. // Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount) // This code is very similar to BIF_sizeof so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[100]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int ispointer = NULL; // identify pointer and how deep it goes int aligntotal = 0; // pointer alignment for total structure int thissize; // used to check if type was found in above array. // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; + Var3.symbol = SYM_INTEGER; // will hold pointer to structure definition string while we parse trough it TCHAR *buf; size_t buf_size; // Use enough buffer to accept any definition in a field. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable) TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; FieldType *field; // used to define a field // Structure object is saved in fixed order // insert_pos is simply increased each time // for loop will enumerate items in same order as it was created IndexType insert_pos = 0; // the new structure object Struct *obj = new Struct(); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; if (TokenToObject(*aParam[0])) { obj->Release(); obj = ((Struct *)TokenToObject(*aParam[0]))->Clone(); if (aParamCount > 2) { obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); obj->ObjectToStruct(TokenToObject(*aParam[2])); } else if (aParamCount > 1) { if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,offset); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); } else { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); } return obj; } // Set initial capacity to avoid multiple expansions. // For simplicity, failure is handled by the loop below. obj->SetInternalCapacity(aParamCount >> 1); // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; // backup offset unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { + // end of structure, align it + if (totalunionsize % aligntotal) + totalunionsize += aligntotal - (totalunionsize % aligntotal); if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; + else if (offset % aligntotal) + offset += aligntotal - (offset % aligntotal); } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set defaults ispointer = false; arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) { obj->Release(); return NULL; } _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) { obj->Release(); return NULL; } else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Pointer if (_tcschr(tempbuf,'*')) ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition from temp buffer to identify key easier StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Trim trailing spaces in case we had a definition like UInt [10] rtrim(tempbuf); } // copy type // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30) { obj->Release(); return NULL; } _tcsncpy(defbuf + 1,tempbuf,buf_size); //_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" ")); defbuf[1 + buf_size] = ' '; defbuf[2 + buf_size] = '\0'; if (StrChrAny(tempbuf, _T(" \t"))) { if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30) { obj->Release(); return NULL; } _tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1); ltrim(keybuf); } else keybuf[0] = '\0'; } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt { _tcscpy(defbuf,_T(" UInt ")); _tcscpy(keybuf,tempbuf); } // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; // align offset if (ispointer) { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } else { if (offset % thissize) offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) { // Out of memory. obj->Release(); return NULL; } offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); } else // type was not found, check for user defined type in variables { Var1.var = NULL; // init to not found Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("*MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; obj->Release(); return NULL; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); // variable found if (Var1.var != NULL) { if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf) { // Whole definition is not a pointer and no key was given so create Structure from variable obj->Release(); if (aParamCount == 1) { if (TokenToObject(*param[0])) { // assume variable is a structure object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); return obj; } // else create structure from string definition return Struct::Create(param,1); } else if (aParamCount > 1) { // more than one parameter was given, copy aParam to param param[1]->symbol = aParam[1]->symbol; param[1]->object = aParam[1]->object; param[1]->value_int64 = aParam[1]->value_int64; param[1]->var = aParam[1]->var; } if (aParamCount > 2) { // more than 2 parameters were given, copy aParam to param param[2]->symbol = aParam[2]->symbol; param[2]->object = aParam[2]->object; param[2]->var = aParam[2]->var; // definition variable is a structure object, clone it, assign memory and init object if (TokenToObject(*param[0])) { obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mMemAllocated = 0; obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; obj->ObjectToStruct(TokenToObject(*aParam[2])); return obj; } return Struct::Create(param,3); } else if (TokenToObject(*param[0])) { // definition variable is a structure object, clone it and assign memory or init object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; return obj; } // else simply create structure from variable and given memory/initobject return Struct::Create(param,2); } // Call BIF_sizeof passing offset in second parameter to align offset if necessary // if field is a pointer we will need its size only if (!ispointer) { param[1]->value_int64 = (__int64)ispointer ? 0 : offset; - BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 2); + param[2]->value_int64 = (__int64)&aligntotal; + BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 3); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure obj->Release(); return NULL; } } else { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } // Insert new field in our structure if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? ptrsize : (int)ResultToken.value_int64,1,1,-1))) { // Out of memory. obj->Release(); return NULL; } if (ispointer) offset += (int)ptrsize * (arraydef ? arraydef : 1); else // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size. { obj->Release(); return NULL; } } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else { // identify that structure object has no fields if (!*keybuf) obj->mTypeOnly = true; buf += _tcslen(buf); } } // align total structure if necessary if (aligntotal && offset % aligntotal) offset += aligntotal - (offset % aligntotal); if (!offset) // structure could not be build { obj->Release(); return NULL; } obj->mSize = offset; if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // second parameter exist and it is digit assumme this is new pointer for our structure obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]); obj->mMemAllocated = 0; } else // no pointer given so allocate memory and fill memory with 0 { // setting the memory after parsing definition saves a call to BIF_sizeof obj->mStructMem = (UINT_PTR *)malloc(offset); obj->mMemAllocated = offset; memset(obj->mStructMem,NULL,offset); } // an object was passed to initialize fields // enumerate trough object and assign values if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 ) obj->ObjectToStruct(TokenToObject(aParamCount == 2 ? *aParam[1] : *aParam[2])); return obj; } // // Struct::ObjectToStruct - Initialize structure from array, object or structure. // void Struct::ObjectToStruct(IObject *objfrom) { ExprTokenType ResultToken, this_token,enum_token,param_tokens[3]; ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 }; TCHAR defbuf[MAX_PATH],buf[MAX_PATH]; int param_count = 3; // Set up enum_token the way Invoke expects: enum_token.symbol = SYM_STRING; enum_token.marker = _T(""); enum_token.mem_to_free = NULL; enum_token.buf = defbuf; // Prepare to call object._NewEnum(): param_tokens[0].symbol = SYM_STRING; param_tokens[0].marker = _T("_NewEnum"); objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1); if (enum_token.mem_to_free) // Invoke returned memory for us to free. free(enum_token.mem_to_free); // Check if object returned an enumerator, otherwise return if (enum_token.symbol != SYM_OBJECT) return; // create variables to use in for loop / for enumeration // these will be deleted afterwards Var *var1 = (Var*)alloca(sizeof(Var)); Var *var2 = (Var*)alloca(sizeof(Var)); var1->mType = var2->mType = VAR_NORMAL; var1->mAttrib = var2->mAttrib = 0; var1->mByteCapacity = var2->mByteCapacity = 0; var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC; // Prepare parameters for the loop below: enum.Next(var1 [, var2]) param_tokens[0].marker = _T("Next"); param_tokens[1].symbol = SYM_VAR; param_tokens[1].var = var1; param_tokens[1].mem_to_free = 0; param_tokens[2].symbol = SYM_VAR; param_tokens[2].var = var2; param_tokens[2].mem_to_free = 0; ExprTokenType result_token; IObject &enumerator = *enum_token.object; // Might perform better as a reference? this_token.symbol = SYM_OBJECT; this_token.object = this; for (;;) { // Set up result_token the way Invoke expects; each Invoke() will change some or all of these: result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; // Call enumerator.Next(var1, var2) enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count); bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token)); if (!next_returned_true) break; this->Invoke(ResultToken,this_token,IT_SET,params+1,2); // release object if it was assigned prevoiously when calling enum.Next if (var1->IsObject()) var1->ReleaseObject(); if (var2->IsObject()) var2->ReleaseObject(); // Free any memory or object which may have been returned by Invoke: if (result_token.mem_to_free) free(result_token.mem_to_free); if (result_token.symbol == SYM_OBJECT) result_token.object->Release(); } // release enumerator and free vars enumerator.Release(); var1->Free(); var2->Free(); } // // Struct::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool Struct::Delete() { return ObjectBase::Delete(); } Struct::~Struct() { if (mMemAllocated > 0) free(mStructMem); if (mFields) { if (mFieldCount) { IndexType i = mFieldCount - 1; // Free keys for ( ; i >= 0 ; --i) { if (mFields[i].mMemAllocated > 0) free(mFields[i].mStructMem); free(mFields[i].key); } } // Free fields array. free(mFields); } } // // Struct::SetPointer - used to set pointer for a field or array item // UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem) { if (mIsPointer) *((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; else *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; return aPointer; } // // Struct::FieldType::Clone - used to clone a field to structure. // Struct *Struct::CloneField(FieldType *field,bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; // if field is an array, set correct size if (obj.mArraySize = field->mArraySize) obj.mSize = field->mSize*obj.mArraySize; else obj.mSize = field->mSize; obj.mIsInteger = field->mIsInteger; obj.mIsPointer = field->mIsPointer; obj.mEncoding = field->mEncoding; obj.mIsUnsigned = field->mIsUnsigned; obj.mVarRef = field->mVarRef; obj.mTypeOnly = 1; obj.mMemAllocated = aIsDynamic ? -1 : 0; return objptr; } // // Struct::Clone - used for cloning structures. // Struct *Struct::Clone(bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; obj.mArraySize = mArraySize; obj.mIsInteger = mIsInteger; obj.mIsPointer = mIsPointer; obj.mEncoding = mEncoding; obj.mIsUnsigned = mIsUnsigned; obj.mSize = mSize; obj.mVarRef = mVarRef; obj.mTypeOnly = mTypeOnly; // -1 will identify a dynamic structure, no memory can be allocated to such obj.mMemAllocated = aIsDynamic ? -1 : 0; // Allocate space in destination object. if (!obj.SetInternalCapacity(mFieldCount)) { obj.Release(); return NULL; } FieldType *fields = obj.mFields; // Newly allocated by above. int failure_count = 0; // See comment below. IndexType i; obj.mFieldCount = mFieldCount; for (i = 0; i < mFieldCount; ++i) { FieldType &dst = fields[i]; FieldType &src = mFields[i]; if ( !(dst.key = _tcsdup(src.key)) ) { // Key allocation failed. // Rather than trying to set up the object so that what we have // so far is valid in order to break out of the loop, continue, // make all fields valid and then allow them to be freed. ++failure_count; } dst.mArraySize = src.mArraySize; dst.mIsInteger = src.mIsInteger; dst.mIsPointer = src.mIsPointer; dst.mEncoding = src.mEncoding; dst.mIsUnsigned = src.mIsUnsigned; dst.mOffset = src.mOffset; dst.mSize = src.mSize; dst.mVarRef = src.mVarRef; dst.mMemAllocated = aIsDynamic ? -1 : 0; } if (failure_count) { // One or more memory allocations failed. It seems best to return a clear failure // indication rather than an incomplete copy. Now that the loop above has finished, // the object's contents are at least valid and it is safe to free the object: obj.Release(); return NULL; } return &obj; } // // Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object. // ResultType STDMETHODCALLTYPE Struct::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) // L40: Revised base mechanism for flexibility and to simplify some aspects. // obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc. { int ptrsize = sizeof(UINT_PTR); FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL ResultType Result = OK; // Used to resolve dynamic structures ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2},ResultToken; // used to clone a dynamic field or structure Struct *objclone = NULL; // used for StrGet/StrPut LPCVOID source_string; int source_length; DWORD flags = WC_NO_BEST_FIT_CHARS; int length = -1; int char_count; // Identify that we need to release/delete field or structure object bool deletefield = false; bool releaseobj = false; int param_count_excluding_rvalue = aParamCount; // target may be altered here to resolve dynamic structure so hold it separately UINT_PTR *target = mStructMem; if (IS_INVOKE_SET) { // Prior validation of ObjSet() param count ensures the result won't be negative: --param_count_excluding_rvalue; // Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best // to have it also block __Set. The code below is disabled to achieve this, with a slight cost to // performance when assigning to a new key in any object which has a base object. (The cost may // depend on how many key-value pairs each base object has.) Note that this doesn't affect meta- // functions defined in *this* base object, since they were already invoked if present. //if (IS_INVOKE_META) //{ // if (param_count_excluding_rvalue == 1) // // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to. // // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue. // param_count_excluding_rvalue = 0; // //else: Allow SET to operate on a field of an object stored in the target's base. // // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc. //} } if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0]))) { // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr if (IS_INVOKE_SET) { if (TokenToObject(*aParam[param_count_excluding_rvalue])) { // Initialize structure using an object. e.g. struct[]:={x:1,y:2} this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue])); // return struct object aResultToken.symbol = SYM_OBJECT; aResultToken.object = this; this->AddRef(); return OK; } if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer { free(mStructMem); mMemAllocated = 0; } // assign new pointer to structure // releasing/deleting structure will not free that memory mStructMem = (UINT_PTR *)TokenToInt64(*aParam[param_count_excluding_rvalue]); } // Return new structure address aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64)mStructMem; return OK; } else { // Array access, struct.1 or struct[1] or struct[1].x ... if (TokenIsPureNumeric(*aParam[0])) { if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1])) { // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) // simply set pointer aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0])); else { // resolve pointer to pointer and set it UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = ((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1))); else { // resolve pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } aResultToken.symbol = SYM_INTEGER; return OK; } // Structure is a reference to variable and not a pointer, get size of structure if (mVarRef && !mIsPointer) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // Variable is a structure object, copy size if (TokenToObject(Var2)) ResultToken.value_int64 = ((Struct *)TokenToObject(Var2))->mSize; else { // use sizeof to find out the size of structure param[0]->symbol = SYM_STRING; Var1.marker = TokenToString(*param[1]); BIF_sizeof(Result,ResultToken,param,1); } } // Check if we have an array, if structure is not array and not pointer, assume array if (mArraySize || !mIsPointer) // if not Array and not pointer assume it is an array target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mIsPointer ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize/(mArraySize ? mArraySize : 1)))); else if (mIsPointer) // resolve pointer target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0])-1)*ptrsize); else // amend target to memory of field target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mVarRef ? ResultToken.value_int64 : mSize)); // Structure has a variable reference and might be a pointer but not pointer to pointer if (mVarRef && mIsPointer < 2) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // variable is a structure object, clone it if (TokenToObject(Var2)) { objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target; if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } // Object to Structure if (IS_INVOKE_SET && TokenToObject(*aParam[1])) { objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // MULTIPARAM if (param_count_excluding_rvalue > 1) { objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; return OK; } else { Var1.symbol = SYM_STRING; Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = (UINT_PTR)target;
tinku99/ahkdll
9840868b5d2fb030f28023338007b70028c1a973
Implemented ahkIsUnicode exported function
diff --git a/source/ComServer.idl b/source/ComServer.idl index 192339f..08f8b6e 100644 --- a/source/ComServer.idl +++ b/source/ComServer.idl @@ -1,74 +1,75 @@ import "wtypes.idl"; [ uuid(A9863C65-8CD4-4069-893D-3B5A3DDFAE88), version(1.0) ] library AutoHotkey { importlib("stdole32.tlb"); #ifdef _WIN64 importlib("stdole2.tlb"); #else importlib("stdole.tlb"); #endif [ uuid(04FFE41B-8FE9-4479-990A-B186EC73F49C), dual, oleautomation ] interface ICOMServer : IDispatch { [id(1)] HRESULT ahktextdll([in,optional] VARIANT script,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] UINT_PTR* hThread); [id(2)] HRESULT ahkdll([in,optional] VARIANT filepath,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] UINT_PTR* hThread); [id(3)] HRESULT ahkPause([in,optional] VARIANT aChangeTo,[out, retval] BOOL* paused); [id(4)] HRESULT ahkReady([out, retval] BOOL* ready); [id(5)] HRESULT ahkFindLabel([in] VARIANT aLabelName,[out, retval] UINT_PTR *pLabel); [id(6)] HRESULT ahkgetvar([in] VARIANT name,[in,optional] VARIANT getVar,[out, retval] VARIANT *returnVal); [id(7)] HRESULT ahkassign([in] VARIANT name,[in,optional] VARIANT value,[out, retval] unsigned int* success); [id(8)] HRESULT ahkExecuteLine([in,optional] VARIANT line,[in,optional] VARIANT aMode,[in,optional] VARIANT wait,[out, retval] UINT_PTR* pLine); [id(9)] HRESULT ahkLabel([in] VARIANT aLabelName,[in,optional] VARIANT nowait,[out, retval] BOOL* success); [id(10)] HRESULT ahkFindFunction([in] VARIANT FuncName,[out, retval] UINT_PTR *pFunc); [id(11)] HRESULT ahkFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] VARIANT* returnVal); [id(12)] HRESULT ahkPostFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] unsigned int* returnVal); [id(13)] HRESULT addScript([in] VARIANT script,[in,optional] VARIANT replace,[out, retval]UINT_PTR* success); [id(14)] HRESULT addFile([in] VARIANT filepath,[in,optional] VARIANT aAllowDuplicateInclude,[in,optional] VARIANT aIgnoreLoadFailure,[out, retval] UINT_PTR* success); [id(15)] HRESULT ahkExec([in] VARIANT script,[out, retval] BOOL* success); [id(16)] HRESULT ahkTerminate([in,optional] VARIANT kill,[out, retval] BOOL* success); [id(17)] HRESULT ahkReload([in,optional] VARIANT timeout); + [id(18)] HRESULT ahkIsUnicode([out, retval] BOOL* IsUnicode); } [ uuid(C00BCC8C-5A04-4392-870F-20AAE1B926B2), helpstring("AutoHotkey Script") ] coclass CoCOMServer { [default] interface ICOMServer; } #ifdef _WIN64 [ uuid(38D00012-DC83-4E17-9BAD-D9DD97902580), helpstring("AutoHotkey Script X64") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else #ifdef _UNICODE [ uuid(C58DCD96-1D6F-4F85-B555-02B7F21F5CAF), helpstring("AutoHotkey Script UNICODE") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else [ uuid(974318D9-A5B2-4FE5-8AC4-33A0C9EBB8B5), helpstring("AutoHotkey Script ANSI") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #endif //Unicode #endif //Win64 } diff --git a/source/ComServerImpl.h b/source/ComServerImpl.h index 828ae9b..61a3c33 100644 --- a/source/ComServerImpl.h +++ b/source/ComServerImpl.h @@ -1,96 +1,97 @@ #ifdef _USRDLL #ifndef MINIDLL #pragma once // ICOMServer interface declaration /////////////////////////////////////////// // // class CoCOMServer : public ICOMServer { // Construction public: CoCOMServer(); ~CoCOMServer(); // IUnknown implementation // virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv) ; virtual ULONG __stdcall AddRef() ; virtual ULONG __stdcall Release() ; //IDispatch implementation virtual HRESULT __stdcall GetTypeInfoCount(UINT* pctinfo); virtual HRESULT __stdcall GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo); virtual HRESULT __stdcall GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid); virtual HRESULT __stdcall Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr); // ICOMServer implementation // virtual HRESULT __stdcall ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /*out*/UINT_PTR* hThread); virtual HRESULT __stdcall ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /*out*/UINT_PTR* hThread); virtual HRESULT __stdcall ahkPause(/*in,optional*/VARIANT aChangeTo, /*out*/BOOL* paused); virtual HRESULT __stdcall ahkReady(/*out*/BOOL* ready); virtual HRESULT __stdcall ahkFindLabel(/*[in]*/ VARIANT aLabelName,/*[out, retval]*/ UINT_PTR *pLabel); virtual HRESULT __stdcall ahkgetvar(/*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT getVar,/*[out, retval]*/ VARIANT *returnVal); virtual HRESULT __stdcall ahkassign(/*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT value,/*[out, retval]*/ unsigned int* success); virtual HRESULT __stdcall ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine); virtual HRESULT __stdcall ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success); virtual HRESULT __stdcall ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR *pFunc); virtual HRESULT __stdcall ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal); virtual HRESULT __stdcall ahkPostFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal); virtual HRESULT __stdcall addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT aExecute,/*[out, retval]*/ UINT_PTR* success); virtual HRESULT __stdcall addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success); virtual HRESULT __stdcall ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success); virtual HRESULT __stdcall ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success); virtual HRESULT __stdcall ahkReload(/*[in]*/ VARIANT timeout); + virtual HRESULT __stdcall ahkIsUnicode(/*out*/BOOL* IsUnicode); private: HRESULT LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID& libid, const CLSID& iid, LCID lcid); // Reference count long m_cRef ; LPTYPEINFO m_ptinfo; // pointer to type-library }; /////////////////////////////////////////////////////////// // // Class factory // class CFactory : public IClassFactory { public: // IUnknown virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv) ; virtual ULONG __stdcall AddRef() ; virtual ULONG __stdcall Release() ; // Interface IClassFactory virtual HRESULT __stdcall CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) ; virtual HRESULT __stdcall LockServer(BOOL bLock) ; // Constructor CFactory() : m_cRef(1) {} // Destructor ~CFactory() {;} private: long m_cRef ; } ; #endif #endif \ No newline at end of file diff --git a/source/ComServer_i.h b/source/ComServer_i.h index df78634..a8f8050 100644 --- a/source/ComServer_i.h +++ b/source/ComServer_i.h @@ -1,294 +1,297 @@ #ifdef _USRDLL #ifndef MINIDLL /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0555 */ /* at Sat Oct 09 20:41:58 2010 */ /* Compiler settings for automcomserver.idl: Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555 protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ /* @@MIDL_FILE_HEADING( ) */ #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __automcomserver_i_h__ #define __automcomserver_i_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ICOMServer_FWD_DEFINED__ #define __ICOMServer_FWD_DEFINED__ typedef interface ICOMServer ICOMServer; #endif /* __ICOMServer_FWD_DEFINED__ */ #ifndef __CoCOMServer_FWD_DEFINED__ #define __CoCOMServer_FWD_DEFINED__ #ifdef __cplusplus typedef class CoCOMServer CoCOMServer; #else typedef struct CoCOMServer CoCOMServer; #endif /* __cplusplus */ #endif /* __CoCOMServer_FWD_DEFINED__ */ /* header files for imported files */ #include "wtypes.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __AutoHotkey_LIBRARY_DEFINED__ #define __AutoHotkey_LIBRARY_DEFINED__ /* library AutoHotkey */ /* [version][uuid] */ DEFINE_GUID(LIBID_AutoHotkey,0xa9863c65, 0x8cd4, 0x4069, 0x89, 0x3d, 0x3b, 0x5a, 0x3d, 0xdf, 0xae, 0x88); #ifndef __ICOMServer_INTERFACE_DEFINED__ #define __ICOMServer_INTERFACE_DEFINED__ /* interface ICOMServer */ /* [object][oleautomation][dual][uuid] */ DEFINE_GUID(IID_ICOMServer,0x4ffe41b, 0x8fe9, 0x4479, 0x99, 0xa, 0xb1, 0x86, 0xec, 0x73, 0xf4, 0x9c); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("04FFE41B-8FE9-4479-990A-B186EC73F49C") ICOMServer : public IDispatch { public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahktextdll( /*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /* [retval][out] */UINT_PTR* hThread) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkdll( /*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /* [retval][out] */UINT_PTR* hThread) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkPause( /*in,optional*/VARIANT aChangeTo,/* [retval][out] */BOOL* paused) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkReady( /* [retval][out] */BOOL* ready) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFindLabel( /*[in]*/ VARIANT aLabelName,/*[out, retval]*/ UINT_PTR *pLabel) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkgetvar( /*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT getVar,/*[out, retval]*/ VARIANT *returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkassign( /*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT value,/*[out, retval]*/ unsigned int* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkExecuteLine( /*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkLabel( /*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFindFunc( /*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR *pFunc) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFunction( /*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkPostFunction( /*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE addScript( /*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ UINT_PTR* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE addFile( /*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkExec( /*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkTerminate( /*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkReload( /*[in,optional]*/ VARIANT timeout) = 0; + public: + virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkIsUnicode( + /* [retval][out] */BOOL* IsUnicode) = 0; }; #else /* C style interface */ typedef struct ICOMServerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ICOMServer * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ICOMServer * This); ULONG ( STDMETHODCALLTYPE *Release )( ICOMServer * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ICOMServer * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ICOMServer * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ICOMServer * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICOMServer * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); /* [id] */ HRESULT ( STDMETHODCALLTYPE *Name )( ICOMServer * This, /* [retval][out] */ BSTR *objectname); END_INTERFACE } ICOMServerVtbl; interface ICOMServer { CONST_VTBL struct ICOMServerVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICOMServer_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICOMServer_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICOMServer_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICOMServer_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICOMServer_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICOMServer_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICOMServer_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICOMServer_Name(This,objectname) \ ( (This)->lpVtbl -> Name(This,objectname) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICOMServer_INTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_CoCOMServer,0xc00bcc8c, 0x5a04, 0x4392, 0x87, 0xf, 0x20, 0xaa, 0xe1, 0xb9, 0x26, 0xb2); #ifdef _WIN64 DEFINE_GUID(CLSID_CoCOMServerOptioal,0x38D00012,0xDC83,0x4E17,0x9B,0xAD,0xD9,0xDD,0x97,0x90,0x25,0x80); #else #ifdef _UNICODE DEFINE_GUID(CLSID_CoCOMServerOptional,0xC58DCD96,0x1D6F,0x4F85,0xB5,0x55,0x02,0xB7,0xF2,0x1F,0x5C,0xAF); #else DEFINE_GUID(CLSID_CoCOMServerOptional,0x974318D9,0xA5B2,0x4FE5,0x8A,0xC4,0x33,0xA0,0xC9,0xEB,0xB8,0xB5); #endif #endif #ifdef __cplusplus class DECLSPEC_UUID("C00BCC8C-5A04-4392-870F-20AAE1B926B2") CoCOMServer; #ifdef _WIN64 class DECLSPEC_UUID("38D00012-DC83-4E17-9BAD-D9DD97902580") #else #ifdef _UNICODE class DECLSPEC_UUID("C58DCD96-1D6F-4F85-B555-02B7F21F5CAF") #else class DECLSPEC_UUID("974318D9-A5B2-4FE5-8AC4-33A0C9EBB8B5") #endif #endif CoCOMServerOptional; #endif #endif /* __AutoHotkey_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif #endif #endif \ No newline at end of file diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 638382d..cb610be 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -229,922 +229,929 @@ int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCm { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(int timeout) { DWORD lpExitCode = 0; if (hThread == 0) return 0; if (timeout < 1) timeout = 500; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < (timeout/100); i++) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0,0,(timeout/10),0); Sleep((timeout/10)); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && *fileName ? fileName : aDefaultDllScript, argv && *argv ? argv : _T(""), args && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && *fileName ? fileName : aDefaultDllScript, argv && *argv ? argv : _T(""), args && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload(int timeout) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } +HRESULT __stdcall CoCOMServer::ahkIsUnicode(/*out*/BOOL* IsUnicode) +{ + if (IsUnicode==NULL) + return ERROR_INVALID_PARAMETER; + *IsUnicode = com_ahkIsUnicode(); + return S_OK; +} HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReload(/*[in,optional]*/ VARIANT timeout) { com_ahkReload(Variant2I(timeout)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; #ifdef DEBUG if (0) // for debugging com #else if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) #endif { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; } // // Server unregistration // STDAPI DllUnregisterServer() { HRESULT hr = UnregisterServer(CLSID_CoCOMServerOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr = UnregisterServer(CLSID_CoCOMServer, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { UnRegisterTypeLib( g_hInstance, NULL); } return hr; } #endif #endif \ No newline at end of file diff --git a/source/exports.cpp b/source/exports.cpp index d11e509..faca2f4 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,552 +1,562 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(int timeout){return ahkTerminate(timeout);} BOOL com_ahkReady(){return ahkReady();} +BOOL com_ahkIsUnicode(){return ahkIsUnicode();} BOOL com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif #endif +EXPORT BOOL ahkIsUnicode() +{ +#ifdef UNICODE + return true; +#else + return false; +#endif +} + EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + sizeof(TCHAR)); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength + sizeof(TCHAR)); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i < 10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); return 0; } else { FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; for (int i = 0;i < aParamsCount;i++) { aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],(_tcslen(*params[i])+1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken.param[i],*params[i]); } //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mStaticVar, func.mStaticVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); g_script.PreprocessLocalVars(func, func.mStaticLazyVar, func.mStaticLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i<10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); switch (aResultToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aResultToken.var->Contents())) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aResultToken.var->Contents()) + 1)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aResultToken.marker)) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aResultToken.marker) + 1)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aResultToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); } return result_to_return_dll; } else // UDF { //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; for (int i = 0;i < aParamsCount;i++) { aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],(_tcslen(*params[i]) + 1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken.param[i],*params[i]); } aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. diff --git a/source/exports.h b/source/exports.h index b1677c6..88aeaec 100644 --- a/source/exports.h +++ b/source/exports.h @@ -1,66 +1,68 @@ // Naveen v1. #define EXPORT __declspec(dllexport) #ifndef exports_h #define exports_h #define EXPORT extern "C" __declspec(dllexport) EXPORT BOOL ahkPause(LPTSTR aChangeTo); EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName); EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar = 0); EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value); EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait); EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait = 0); EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) ; EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1 = _T(""), LPTSTR param2 = _T(""), LPTSTR param3 = _T(""), LPTSTR param4 = _T(""), LPTSTR param5 = _T(""), LPTSTR param6 = _T(""), LPTSTR param7 = _T(""), LPTSTR param8 = _T(""), LPTSTR param9 = _T(""), LPTSTR param10 = _T("")); EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1 = _T(""), LPTSTR param2 = _T(""), LPTSTR param3 = _T(""), LPTSTR param4 = _T(""), LPTSTR param5 = _T(""), LPTSTR param6 = _T(""), LPTSTR param7 = _T(""), LPTSTR param8 = _T(""), LPTSTR param9 = _T(""), LPTSTR param10 = _T("")); #ifndef AUTOHOTKEYSC EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude = false, int aIgnoreLoadFailure = 0); EXPORT UINT_PTR addScript(LPTSTR script, int aReplace = 0); EXPORT BOOL ahkExec(LPTSTR script); #endif void callFuncDllVariant(FuncAndToken *aFuncAndToken); void callFuncDll(FuncAndToken *aFuncAndToken); int initPlugins(); #ifdef _USRDLL EXPORT UINT_PTR ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); EXPORT UINT_PTR ahktextdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); EXPORT BOOL ahkTerminate(int timeout); EXPORT BOOL com_ahkTerminate(int timeout); EXPORT BOOL ahkReady(); EXPORT BOOL com_ahkReady(); EXPORT BOOL ahkReload(int timeout); EXPORT BOOL com_ahkReload(); void reloadDll(); ResultType terminateDll(); +EXPORT BOOL ahkIsUnicode(); #endif #endif #ifndef MINIDLL //COM virtual functions declaration BOOL com_ahkPause(LPTSTR aChangeTo); UINT_PTR com_ahkFindLabel(LPTSTR aLabelName); // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar); // unsigned int com_ahkassign(LPTSTR name, LPTSTR value); UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait); BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait); UINT_PTR com_ahkFindFunc(LPTSTR funcname); // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10); unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10); #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute); BOOL com_ahkExec(LPTSTR script); UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure); #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); UINT_PTR com_ahktextdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); BOOL com_ahkTerminate(int timeout); BOOL com_ahkReady(); +BOOL com_ahkIsUnicode(); BOOL com_ahkReload(int timeout); #endif #endif \ No newline at end of file
tinku99/ahkdll
310535b403756f8f9f0b19bc22f5b555f7528419
Fixed sizeof bug leaving current function after static init
diff --git a/source/script_object_bif.cpp b/source/script_object_bif.cpp index 664ef7e..ef21bb8 100644 --- a/source/script_object_bif.cpp +++ b/source/script_object_bif.cpp @@ -1,688 +1,684 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "globaldata.h" #include "script.h" #include "script_object.h" // // BIF_Struct - Create structure // BIF_DECL(BIF_Struct) { // At least the definition for structure must be given if (!aParamCount) return; IObject *obj = Struct::Create(aParam,aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } // indicate error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_sizeof - sizeof() for structures and default types // BIF_DECL(BIF_sizeof) // This code is very similar to BIF_Struct so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[10]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int aligntotal = 0; // pointer alignment for total structure int thissize; // used to save size returned from IsDefaultType // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2}; // will hold pointer to structure definition while we parse it TCHAR *buf; size_t buf_size; // Should be enough buffer to accept any definition and name. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; // Set result to empty string to identify error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; // if first parameter is an object (struct), simply return its size if (TokenToObject(*aParam[0])) { aResultToken.symbol = SYM_INTEGER; Struct *obj = (Struct*)TokenToObject(*aParam[0]); aResultToken.value_int64 = obj->mSize; return; } if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // an offset was given, set starting offset offset = (int)TokenToInt64(*aParam[1]); Var2.value_int64 = (__int64)offset; } // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // now restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set default arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) return; _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) return; else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } // Pointer, while loop will continue here because we only need size if (_tcschr(tempbuf,'*')) { offset += ptrsize * (arraydef ? arraydef : 1); // align offset for pointer if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; // update offset if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now and continue if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); continue; } // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t ["))) > MAX_VAR_NAME_LENGTH*2 + 30) return; _tcsncpy(defbuf + 1,tempbuf,_tcscspn(tempbuf,_T("\t ["))); _tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t [")),_T(" ")); } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt _tcscpy(defbuf,_T(" UInt ")); // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; offset += thissize * (arraydef ? arraydef : 1); // align offset if (thissize > 1 && offset % thissize) { offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } } else // type was not found, check for user defined type in variables { Var1.var = NULL; Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); + Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); + g->CurrentFunc = bkpfunc; } else // release object and return { - if (bkpfunc) - g->CurrentFunc = bkpfunc; + g->CurrentFunc = bkpfunc; return; } } - if (g->CurrentFunc) - { + else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); - // restore CurrentFunc - if (bkpfunc) - g->CurrentFunc = bkpfunc; - } // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); if (Var1.var != NULL) { // Call BIF_sizeof passing offset in second parameter to align if necessary param[1]->value_int64 = (__int64)offset; BIF_sizeof(Result,ResultToken,param,2); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure return; } // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size, return empty string. return; } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); } if (aligntotal && offset % aligntotal) // align only if offset was not given offset += aligntotal - (offset % aligntotal); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = offset; } // // BIF_ObjCreate - Object() // BIF_DECL(BIF_ObjCreate) { IObject *obj = NULL; if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { if (obj = TokenToObject(*aParam[0])) { // Allow &obj == Object(obj), but AddRef() for equivalence with ComObjActive(comobj). obj->AddRef(); aResultToken.value_int64 = (__int64)obj; return; // symbol is already SYM_INTEGER. } obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = Object::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // BIF_ObjArray - Array(items*) // BIF_DECL(BIF_ObjArray) { Object *obj = Object::Create(); if (obj) { if (!aParamCount || obj->InsertAt(0, 1, aParam, aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; } obj->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_IsObject - IsObject(obj) // BIF_DECL(BIF_IsObject) // IsObject(obj) is currently equivalent to (obj && obj=""), but much more intuitive. { int i; for (i = 0; i < aParamCount && TokenToObject(*aParam[i]); ++i); aResultToken.value_int64 = (__int64)(i == aParamCount); // TRUE if all are objects. } // // BIF_ObjInvoke - Handles ObjGet/Set/Call() and get/set/call syntax. // BIF_DECL(BIF_ObjInvoke) { int invoke_type; IObject *obj; ExprTokenType *obj_param; // Since ObjGet/ObjSet/ObjCall are not publicly accessible as functions, Func::mName // (passed via aResultToken.marker) contains the actual flag rather than a name. invoke_type = (int)(INT_PTR)aResultToken.marker; // Set default return value; ONLY AFTER THE ABOVE. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); obj_param = *aParam; // aParam[0]. Load-time validation has ensured at least one parameter was specified. ++aParam; --aParamCount; // The following is used in place of TokenToObject to bypass #Warn UseUnset: if (obj_param->symbol == SYM_OBJECT) obj = obj_param->object; else if (obj_param->symbol == SYM_VAR && obj_param->var->HasObject()) obj = obj_param->var->Object(); else obj = NULL; if (obj) { bool param_is_var = obj_param->symbol == SYM_VAR; if (param_is_var) // Since the variable may be cleared as a side-effect of the invocation, call AddRef to ensure the object does not expire prematurely. // This is not necessary for SYM_OBJECT since that reference is already counted and cannot be released before we return. Each object // could take care not to delete itself prematurely, but it seems more proper, more reliable and more maintainable to handle it here. obj->AddRef(); aResult = obj->Invoke(aResultToken, *obj_param, invoke_type, aParam, aParamCount); if (param_is_var) obj->Release(); } // Invoke meta-functions of g_MetaObject. else if (INVOKE_NOT_HANDLED == (aResult = g_MetaObject.Invoke(aResultToken, *obj_param, invoke_type | IF_META, aParam, aParamCount))) { // Since above did not handle it, check for attempts to access .base of non-object value (g_MetaObject itself). if ( invoke_type != IT_CALL // Exclude things like "".base(). && aParamCount > (invoke_type == IT_SET ? 2 : 0) // SET is supported only when an index is specified: "".base[x]:=y && !_tcsicmp(TokenToString(*aParam[0]), _T("base")) ) { if (aParamCount > 1) // "".base[x] or similar { // Re-invoke g_MetaObject without meta flag or "base" param. ExprTokenType base_token; base_token.symbol = SYM_OBJECT; base_token.object = &g_MetaObject; g_MetaObject.Invoke(aResultToken, base_token, invoke_type, aParam + 1, aParamCount - 1); } else // "".base { // Return a reference to g_MetaObject. No need to AddRef as g_MetaObject ignores it. aResultToken.symbol = SYM_OBJECT; aResultToken.object = &g_MetaObject; } } else { // Since it wasn't handled (not even by g_MetaObject), maybe warn at this point: if (obj_param->symbol == SYM_VAR) obj_param->var->MaybeWarnUninitialized(); } } if (aResult == INVOKE_NOT_HANDLED) aResult = OK; } // // BIF_ObjGetInPlace - Handles part of a compound assignment like x.y += z. // BIF_DECL(BIF_ObjGetInPlace) { // Since the most common cases have two params, the "param count" param is omitted in // those cases. Otherwise we have one visible parameter, which indicates the number of // actual parameters below it on the stack. aParamCount = aParamCount ? (int)TokenToInt64(*aParam[0]) : 2; // x[<n-1 params>] : x.y BIF_ObjInvoke(aResult, aResultToken, aParam - aParamCount, aParamCount); } // // BIF_ObjNew - Handles "new" as in "new Class()". // BIF_DECL(BIF_ObjNew) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ExprTokenType *class_token = aParam[0]; // Save this to be restored later. IObject *class_object = TokenToObject(*class_token); if (!class_object) return; Object *new_object = Object::Create(); if (!new_object) return; new_object->SetBase(class_object); ExprTokenType name_token, this_token; this_token.symbol = SYM_OBJECT; this_token.object = new_object; name_token.symbol = SYM_STRING; aParam[0] = &name_token; ResultType result; LPTSTR buf = aResultToken.buf; // In case Invoke overwrites it via the union. // __Init was added so that instance variables can be initialized in the correct order // (beginning at the root class and ending at class_object) before __New is called. // It shouldn't be explicitly defined by the user, but auto-generated in DefineClassVars(). name_token.marker = _T("__Init"); result = class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, 1); if (result != INVOKE_NOT_HANDLED) { // See similar section below for comments. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Reset to defaults for __New, invoked below. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); aResultToken.buf = buf; if (result == FAIL) { aParam[0] = class_token; // Restore it to original caller-supplied value. return; } } // __New may be defined by the script for custom initialization code. name_token.marker = Object::sMetaFuncName[4]; // __New if (class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, aParamCount) != EARLY_RETURN) { // Although it isn't likely to happen, if __New points at a built-in function or if mBase // (or an ancestor) is not an Object (i.e. it's a ComObject), aResultToken can be set even when // the result is not EARLY_RETURN. So make sure to clean up any result we're not going to use. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { // This can be done by our caller, but is done here for maintainability; i.e. because // some callers might expect mem_to_free to be NULL when the result isn't a string. free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Either it wasn't handled (i.e. neither this class nor any of its super-classes define __New()), // or there was no explicit "return", so just return the new object. aResultToken.symbol = SYM_OBJECT; aResultToken.object = this_token.object; } else new_object->Release(); aParam[0] = class_token; } // // BIF_ObjIncDec - Handles pre/post-increment/decrement for object fields, such as ++x[y]. // BIF_DECL(BIF_ObjIncDec) { // Func::mName (which aResultToken.marker is set to) has been overloaded to pass // the type of increment/decrement to be performed on this object's field. SymbolType op = (SymbolType)(INT_PTR)aResultToken.marker; ExprTokenType temp_result, current_value, value_to_set; // Set the defaults expected by BIF_ObjInvoke: temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_GET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Retrieve the current value. Do it this way instead of calling Object::Invoke // so that if aParam[0] is not an object, g_MetaObject is correctly invoked. BIF_ObjInvoke(aResult, temp_result, aParam, aParamCount); if (aResult == FAIL || aResult == EARLY_EXIT) return; // Change SYM_STRING to SYM_OPERAND so below may treat it as a numeric string. if (temp_result.symbol == SYM_STRING) { temp_result.symbol = SYM_OPERAND; temp_result.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } switch (value_to_set.symbol = current_value.symbol = TokenIsPureNumeric(temp_result)) { case PURE_INTEGER: value_to_set.value_int64 = (current_value.value_int64 = TokenToInt64(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; case PURE_FLOAT: value_to_set.value_double = (current_value.value_double = TokenToDouble(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; } // Free the object or string returned by BIF_ObjInvoke, if applicable. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); if (current_value.symbol == PURE_NOT_NUMERIC) { // Value is non-numeric, so assign and return "". value_to_set.symbol = SYM_STRING; value_to_set.marker = _T(""); //current_value.symbol = SYM_STRING; // Already done (SYM_STRING == PURE_NOT_NUMERIC). current_value.marker = _T(""); } // Although it's likely our caller's param array has enough space to hold the extra // parameter, there's no way to know for sure whether it's safe, so we allocate our own: ExprTokenType **param = (ExprTokenType **)_alloca((aParamCount + 1) * sizeof(ExprTokenType *)); memcpy(param, aParam, aParamCount * sizeof(ExprTokenType *)); // Copy caller's param pointers. param[aParamCount++] = &value_to_set; // Append new value as the last parameter. if (op == SYM_PRE_INCREMENT || op == SYM_PRE_DECREMENT) { aResultToken.marker = (LPTSTR)IT_SET; // Set the new value and pass the return value of the invocation back to our caller. // This should be consistent with something like x.y := x.y + 1. BIF_ObjInvoke(aResult, aResultToken, param, aParamCount); } else // SYM_POST_INCREMENT || SYM_POST_DECREMENT { // Must be re-initialized (and must use IT_SET instead of IT_GET): temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_SET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Set the new value. BIF_ObjInvoke(aResult, temp_result, param, aParamCount); // Dispose of the result safely. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); // Return the previous value. aResultToken.symbol = current_value.symbol; aResultToken.value_int64 = current_value.value_int64; // Union copy. } } // // Functions for accessing built-in methods (even if obscured by a user-defined method). // #define BIF_METHOD(name) \ BIF_DECL(BIF_Obj##name) \ { \ aResultToken.symbol = SYM_STRING; \ aResultToken.marker = _T(""); \ \ Object *obj = dynamic_cast<Object*>(TokenToObject(*aParam[0])); \ if (obj) \ obj->_##name(aResultToken, aParam + 1, aParamCount - 1); \ } BIF_METHOD(Insert) BIF_METHOD(Remove) BIF_METHOD(GetCapacity) BIF_METHOD(SetCapacity) BIF_METHOD(GetAddress) BIF_METHOD(MaxIndex) BIF_METHOD(MinIndex) BIF_METHOD(NewEnum) BIF_METHOD(HasKey) BIF_METHOD(Clone) // // ObjAddRef/ObjRelease - used with pointers rather than object references. // BIF_DECL(BIF_ObjAddRefRelease) { IObject *obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)4096) // Rule out some obvious errors. { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[3]) == 'A') aResultToken.value_int64 = obj->AddRef(); else aResultToken.value_int64 = obj->Release(); } \ No newline at end of file
tinku99/ahkdll
74e47be208068ed611a85debe1669439a249fd20
Fixed a bug in command line parameters for Win32a
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 6b82ebb..638382d 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,691 +1,691 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; // Naveen v1. hThread2 and threadCount // Todo: remove these as multithreading was implemented // with multiple loading of the dll under separate names. static int threadCount = 1 ; static HANDLE hThread2; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); // Unregister window class registered in Script::CreateWindows #ifndef MINIDLL #ifdef UNICODE if (g_ClassRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else if (g_ClassRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); if (g_ClassSplashRegistered) UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif #endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE - param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); - WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); + param = (TCHAR *) _alloca(wcslen(dllargv[i])+1); + WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(int timeout) { DWORD lpExitCode = 0; if (hThread == 0) return 0; if (timeout < 1) timeout = 500; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < (timeout/100); i++) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0,0,(timeout/10),0); Sleep((timeout/10)); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && *fileName ? fileName : aDefaultDllScript, argv && *argv ? argv : _T(""), args && *args ? args : _T(""))) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(fileName && *fileName ? fileName : aDefaultDllScript, argv && *argv ? argv : _T(""), args && *args ? args : _T(""))) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload(int timeout) { ahkTerminate(timeout); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION;
tinku99/ahkdll
c0098c370e79b8f1581b3f9b394d46f0b70f8186
Fixed a bug in Struct and sizeof for arrays in structures
diff --git a/source/script_object_bif.cpp b/source/script_object_bif.cpp index 77ab508..664ef7e 100644 --- a/source/script_object_bif.cpp +++ b/source/script_object_bif.cpp @@ -1,688 +1,688 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "globaldata.h" #include "script.h" #include "script_object.h" // // BIF_Struct - Create structure // BIF_DECL(BIF_Struct) { // At least the definition for structure must be given if (!aParamCount) return; IObject *obj = Struct::Create(aParam,aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } // indicate error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_sizeof - sizeof() for structures and default types // BIF_DECL(BIF_sizeof) // This code is very similar to BIF_Struct so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[10]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int aligntotal = 0; // pointer alignment for total structure int thissize; // used to save size returned from IsDefaultType // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2}; // will hold pointer to structure definition while we parse it TCHAR *buf; size_t buf_size; // Should be enough buffer to accept any definition and name. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; // Set result to empty string to identify error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; // if first parameter is an object (struct), simply return its size if (TokenToObject(*aParam[0])) { aResultToken.symbol = SYM_INTEGER; Struct *obj = (Struct*)TokenToObject(*aParam[0]); aResultToken.value_int64 = obj->mSize; return; } if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // an offset was given, set starting offset offset = (int)TokenToInt64(*aParam[1]); Var2.value_int64 = (__int64)offset; } // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // now restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set default arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) return; _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) return; else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } // Pointer, while loop will continue here because we only need size if (_tcschr(tempbuf,'*')) { offset += ptrsize * (arraydef ? arraydef : 1); // align offset for pointer if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; // update offset if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now and continue if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); continue; } // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t ["))) > MAX_VAR_NAME_LENGTH*2 + 30) return; _tcsncpy(defbuf + 1,tempbuf,_tcscspn(tempbuf,_T("\t ["))); _tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t [")),_T(" ")); } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt _tcscpy(defbuf,_T(" UInt ")); // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; offset += thissize * (arraydef ? arraydef : 1); // align offset if (thissize > 1 && offset % thissize) { offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } } else // type was not found, check for user defined type in variables { Var1.var = NULL; Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); } else // release object and return { if (bkpfunc) g->CurrentFunc = bkpfunc; return; } } if (g->CurrentFunc) { Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // restore CurrentFunc if (bkpfunc) g->CurrentFunc = bkpfunc; } // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); if (Var1.var != NULL) { // Call BIF_sizeof passing offset in second parameter to align if necessary param[1]->value_int64 = (__int64)offset; BIF_sizeof(Result,ResultToken,param,2); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure return; } // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += - offset = (int)ResultToken.value_int64 * (arraydef ? arraydef : 1); + offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size, return empty string. return; } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); } if (aligntotal && offset % aligntotal) // align only if offset was not given offset += aligntotal - (offset % aligntotal); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = offset; } // // BIF_ObjCreate - Object() // BIF_DECL(BIF_ObjCreate) { IObject *obj = NULL; if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { if (obj = TokenToObject(*aParam[0])) { // Allow &obj == Object(obj), but AddRef() for equivalence with ComObjActive(comobj). obj->AddRef(); aResultToken.value_int64 = (__int64)obj; return; // symbol is already SYM_INTEGER. } obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = Object::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // BIF_ObjArray - Array(items*) // BIF_DECL(BIF_ObjArray) { Object *obj = Object::Create(); if (obj) { if (!aParamCount || obj->InsertAt(0, 1, aParam, aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; } obj->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_IsObject - IsObject(obj) // BIF_DECL(BIF_IsObject) // IsObject(obj) is currently equivalent to (obj && obj=""), but much more intuitive. { int i; for (i = 0; i < aParamCount && TokenToObject(*aParam[i]); ++i); aResultToken.value_int64 = (__int64)(i == aParamCount); // TRUE if all are objects. } // // BIF_ObjInvoke - Handles ObjGet/Set/Call() and get/set/call syntax. // BIF_DECL(BIF_ObjInvoke) { int invoke_type; IObject *obj; ExprTokenType *obj_param; // Since ObjGet/ObjSet/ObjCall are not publicly accessible as functions, Func::mName // (passed via aResultToken.marker) contains the actual flag rather than a name. invoke_type = (int)(INT_PTR)aResultToken.marker; // Set default return value; ONLY AFTER THE ABOVE. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); obj_param = *aParam; // aParam[0]. Load-time validation has ensured at least one parameter was specified. ++aParam; --aParamCount; // The following is used in place of TokenToObject to bypass #Warn UseUnset: if (obj_param->symbol == SYM_OBJECT) obj = obj_param->object; else if (obj_param->symbol == SYM_VAR && obj_param->var->HasObject()) obj = obj_param->var->Object(); else obj = NULL; if (obj) { bool param_is_var = obj_param->symbol == SYM_VAR; if (param_is_var) // Since the variable may be cleared as a side-effect of the invocation, call AddRef to ensure the object does not expire prematurely. // This is not necessary for SYM_OBJECT since that reference is already counted and cannot be released before we return. Each object // could take care not to delete itself prematurely, but it seems more proper, more reliable and more maintainable to handle it here. obj->AddRef(); aResult = obj->Invoke(aResultToken, *obj_param, invoke_type, aParam, aParamCount); if (param_is_var) obj->Release(); } // Invoke meta-functions of g_MetaObject. else if (INVOKE_NOT_HANDLED == (aResult = g_MetaObject.Invoke(aResultToken, *obj_param, invoke_type | IF_META, aParam, aParamCount))) { // Since above did not handle it, check for attempts to access .base of non-object value (g_MetaObject itself). if ( invoke_type != IT_CALL // Exclude things like "".base(). && aParamCount > (invoke_type == IT_SET ? 2 : 0) // SET is supported only when an index is specified: "".base[x]:=y && !_tcsicmp(TokenToString(*aParam[0]), _T("base")) ) { if (aParamCount > 1) // "".base[x] or similar { // Re-invoke g_MetaObject without meta flag or "base" param. ExprTokenType base_token; base_token.symbol = SYM_OBJECT; base_token.object = &g_MetaObject; g_MetaObject.Invoke(aResultToken, base_token, invoke_type, aParam + 1, aParamCount - 1); } else // "".base { // Return a reference to g_MetaObject. No need to AddRef as g_MetaObject ignores it. aResultToken.symbol = SYM_OBJECT; aResultToken.object = &g_MetaObject; } } else { // Since it wasn't handled (not even by g_MetaObject), maybe warn at this point: if (obj_param->symbol == SYM_VAR) obj_param->var->MaybeWarnUninitialized(); } } if (aResult == INVOKE_NOT_HANDLED) aResult = OK; } // // BIF_ObjGetInPlace - Handles part of a compound assignment like x.y += z. // BIF_DECL(BIF_ObjGetInPlace) { // Since the most common cases have two params, the "param count" param is omitted in // those cases. Otherwise we have one visible parameter, which indicates the number of // actual parameters below it on the stack. aParamCount = aParamCount ? (int)TokenToInt64(*aParam[0]) : 2; // x[<n-1 params>] : x.y BIF_ObjInvoke(aResult, aResultToken, aParam - aParamCount, aParamCount); } // // BIF_ObjNew - Handles "new" as in "new Class()". // BIF_DECL(BIF_ObjNew) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ExprTokenType *class_token = aParam[0]; // Save this to be restored later. IObject *class_object = TokenToObject(*class_token); if (!class_object) return; Object *new_object = Object::Create(); if (!new_object) return; new_object->SetBase(class_object); ExprTokenType name_token, this_token; this_token.symbol = SYM_OBJECT; this_token.object = new_object; name_token.symbol = SYM_STRING; aParam[0] = &name_token; ResultType result; LPTSTR buf = aResultToken.buf; // In case Invoke overwrites it via the union. // __Init was added so that instance variables can be initialized in the correct order // (beginning at the root class and ending at class_object) before __New is called. // It shouldn't be explicitly defined by the user, but auto-generated in DefineClassVars(). name_token.marker = _T("__Init"); result = class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, 1); if (result != INVOKE_NOT_HANDLED) { // See similar section below for comments. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Reset to defaults for __New, invoked below. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); aResultToken.buf = buf; if (result == FAIL) { aParam[0] = class_token; // Restore it to original caller-supplied value. return; } } // __New may be defined by the script for custom initialization code. name_token.marker = Object::sMetaFuncName[4]; // __New if (class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, aParamCount) != EARLY_RETURN) { // Although it isn't likely to happen, if __New points at a built-in function or if mBase // (or an ancestor) is not an Object (i.e. it's a ComObject), aResultToken can be set even when // the result is not EARLY_RETURN. So make sure to clean up any result we're not going to use. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { // This can be done by our caller, but is done here for maintainability; i.e. because // some callers might expect mem_to_free to be NULL when the result isn't a string. free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Either it wasn't handled (i.e. neither this class nor any of its super-classes define __New()), // or there was no explicit "return", so just return the new object. aResultToken.symbol = SYM_OBJECT; aResultToken.object = this_token.object; } else new_object->Release(); aParam[0] = class_token; } // // BIF_ObjIncDec - Handles pre/post-increment/decrement for object fields, such as ++x[y]. // BIF_DECL(BIF_ObjIncDec) { // Func::mName (which aResultToken.marker is set to) has been overloaded to pass // the type of increment/decrement to be performed on this object's field. SymbolType op = (SymbolType)(INT_PTR)aResultToken.marker; ExprTokenType temp_result, current_value, value_to_set; // Set the defaults expected by BIF_ObjInvoke: temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_GET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Retrieve the current value. Do it this way instead of calling Object::Invoke // so that if aParam[0] is not an object, g_MetaObject is correctly invoked. BIF_ObjInvoke(aResult, temp_result, aParam, aParamCount); if (aResult == FAIL || aResult == EARLY_EXIT) return; // Change SYM_STRING to SYM_OPERAND so below may treat it as a numeric string. if (temp_result.symbol == SYM_STRING) { temp_result.symbol = SYM_OPERAND; temp_result.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } switch (value_to_set.symbol = current_value.symbol = TokenIsPureNumeric(temp_result)) { case PURE_INTEGER: value_to_set.value_int64 = (current_value.value_int64 = TokenToInt64(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; case PURE_FLOAT: value_to_set.value_double = (current_value.value_double = TokenToDouble(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; } // Free the object or string returned by BIF_ObjInvoke, if applicable. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); if (current_value.symbol == PURE_NOT_NUMERIC) { // Value is non-numeric, so assign and return "". value_to_set.symbol = SYM_STRING; value_to_set.marker = _T(""); //current_value.symbol = SYM_STRING; // Already done (SYM_STRING == PURE_NOT_NUMERIC). current_value.marker = _T(""); } // Although it's likely our caller's param array has enough space to hold the extra // parameter, there's no way to know for sure whether it's safe, so we allocate our own: ExprTokenType **param = (ExprTokenType **)_alloca((aParamCount + 1) * sizeof(ExprTokenType *)); memcpy(param, aParam, aParamCount * sizeof(ExprTokenType *)); // Copy caller's param pointers. param[aParamCount++] = &value_to_set; // Append new value as the last parameter. if (op == SYM_PRE_INCREMENT || op == SYM_PRE_DECREMENT) { aResultToken.marker = (LPTSTR)IT_SET; // Set the new value and pass the return value of the invocation back to our caller. // This should be consistent with something like x.y := x.y + 1. BIF_ObjInvoke(aResult, aResultToken, param, aParamCount); } else // SYM_POST_INCREMENT || SYM_POST_DECREMENT { // Must be re-initialized (and must use IT_SET instead of IT_GET): temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_SET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Set the new value. BIF_ObjInvoke(aResult, temp_result, param, aParamCount); // Dispose of the result safely. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); // Return the previous value. aResultToken.symbol = current_value.symbol; aResultToken.value_int64 = current_value.value_int64; // Union copy. } } // // Functions for accessing built-in methods (even if obscured by a user-defined method). // #define BIF_METHOD(name) \ BIF_DECL(BIF_Obj##name) \ { \ aResultToken.symbol = SYM_STRING; \ aResultToken.marker = _T(""); \ \ Object *obj = dynamic_cast<Object*>(TokenToObject(*aParam[0])); \ if (obj) \ obj->_##name(aResultToken, aParam + 1, aParamCount - 1); \ } BIF_METHOD(Insert) BIF_METHOD(Remove) BIF_METHOD(GetCapacity) BIF_METHOD(SetCapacity) BIF_METHOD(GetAddress) BIF_METHOD(MaxIndex) BIF_METHOD(MinIndex) BIF_METHOD(NewEnum) BIF_METHOD(HasKey) BIF_METHOD(Clone) // // ObjAddRef/ObjRelease - used with pointers rather than object references. // BIF_DECL(BIF_ObjAddRefRelease) { IObject *obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)4096) // Rule out some obvious errors. { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[3]) == 'A') aResultToken.value_int64 = obj->AddRef(); else aResultToken.value_int64 = obj->Release(); } \ No newline at end of file diff --git a/source/script_struct.cpp b/source/script_struct.cpp index bf1ba7e..318b9c6 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -1,887 +1,887 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "application.h" #include "globaldata.h" #include "script.h" #include "TextIO.h" #include "script_object.h" // // Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set. // Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount) // This code is very similar to BIF_sizeof so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[100]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int ispointer = NULL; // identify pointer and how deep it goes int aligntotal = 0; // pointer alignment for total structure int thissize; // used to check if type was found in above array. // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; // will hold pointer to structure definition string while we parse trough it TCHAR *buf; size_t buf_size; // Use enough buffer to accept any definition in a field. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable) TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; FieldType *field; // used to define a field // Structure object is saved in fixed order // insert_pos is simply increased each time // for loop will enumerate items in same order as it was created IndexType insert_pos = 0; // the new structure object Struct *obj = new Struct(); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; if (TokenToObject(*aParam[0])) { obj->Release(); obj = ((Struct *)TokenToObject(*aParam[0]))->Clone(); if (aParamCount > 2) { obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); obj->ObjectToStruct(TokenToObject(*aParam[2])); } else if (aParamCount > 1) { if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,offset); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); } else { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); } return obj; } // Set initial capacity to avoid multiple expansions. // For simplicity, failure is handled by the loop below. obj->SetInternalCapacity(aParamCount >> 1); // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; // backup offset unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set defaults ispointer = false; arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) { obj->Release(); return NULL; } _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) { obj->Release(); return NULL; } else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Pointer if (_tcschr(tempbuf,'*')) ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition from temp buffer to identify key easier StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Trim trailing spaces in case we had a definition like UInt [10] rtrim(tempbuf); } // copy type // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30) { obj->Release(); return NULL; } _tcsncpy(defbuf + 1,tempbuf,buf_size); //_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" ")); defbuf[1 + buf_size] = ' '; defbuf[2 + buf_size] = '\0'; if (StrChrAny(tempbuf, _T(" \t"))) { if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30) { obj->Release(); return NULL; } _tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1); ltrim(keybuf); } else keybuf[0] = '\0'; } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt { _tcscpy(defbuf,_T(" UInt ")); _tcscpy(keybuf,tempbuf); } // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!_tcscmp(defbuf,_T(" bool "))) thissize = 1; // align offset if (ispointer) { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } else { if (offset % thissize) offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) { // Out of memory. obj->Release(); return NULL; } offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); } else // type was not found, check for user defined type in variables { Var1.var = NULL; // init to not found Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("*MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; obj->Release(); return NULL; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); // variable found if (Var1.var != NULL) { if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf) { // Whole definition is not a pointer and no key was given so create Structure from variable obj->Release(); if (aParamCount == 1) { if (TokenToObject(*param[0])) { // assume variable is a structure object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); return obj; } // else create structure from string definition return Struct::Create(param,1); } else if (aParamCount > 1) { // more than one parameter was given, copy aParam to param param[1]->symbol = aParam[1]->symbol; param[1]->object = aParam[1]->object; param[1]->value_int64 = aParam[1]->value_int64; param[1]->var = aParam[1]->var; } if (aParamCount > 2) { // more than 2 parameters were given, copy aParam to param param[2]->symbol = aParam[2]->symbol; param[2]->object = aParam[2]->object; param[2]->var = aParam[2]->var; // definition variable is a structure object, clone it, assign memory and init object if (TokenToObject(*param[0])) { obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mMemAllocated = 0; obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; obj->ObjectToStruct(TokenToObject(*aParam[2])); return obj; } return Struct::Create(param,3); } else if (TokenToObject(*param[0])) { // definition variable is a structure object, clone it and assign memory or init object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; return obj; } // else simply create structure from variable and given memory/initobject return Struct::Create(param,2); } // Call BIF_sizeof passing offset in second parameter to align offset if necessary // if field is a pointer we will need its size only if (!ispointer) { param[1]->value_int64 = (__int64)ispointer ? 0 : offset; BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 2); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure obj->Release(); return NULL; } } else { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } // Insert new field in our structure if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? ptrsize : (int)ResultToken.value_int64,1,1,-1))) { // Out of memory. obj->Release(); return NULL; } if (ispointer) offset += (int)ptrsize * (arraydef ? arraydef : 1); else // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += - offset = (int)ResultToken.value_int64 * (arraydef ? arraydef : 1); + offset = (int)ResultToken.value_int64 + (arraydef ? ((arraydef - 1) * ((int)ResultToken.value_int64 - offset)) : 0); } else // No variable was found and it is not default type so we can't determine size. { obj->Release(); return NULL; } } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else { // identify that structure object has no fields if (!*keybuf) obj->mTypeOnly = true; buf += _tcslen(buf); } } // align total structure if necessary if (aligntotal && offset % aligntotal) offset += aligntotal - (offset % aligntotal); if (!offset) // structure could not be build { obj->Release(); return NULL; } obj->mSize = offset; if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // second parameter exist and it is digit assumme this is new pointer for our structure obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]); obj->mMemAllocated = 0; } else // no pointer given so allocate memory and fill memory with 0 { // setting the memory after parsing definition saves a call to BIF_sizeof obj->mStructMem = (UINT_PTR *)malloc(offset); obj->mMemAllocated = offset; memset(obj->mStructMem,NULL,offset); } // an object was passed to initialize fields // enumerate trough object and assign values if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 ) obj->ObjectToStruct(TokenToObject(aParamCount == 2 ? *aParam[1] : *aParam[2])); return obj; } // // Struct::ObjectToStruct - Initialize structure from array, object or structure. // void Struct::ObjectToStruct(IObject *objfrom) { ExprTokenType ResultToken, this_token,enum_token,param_tokens[3]; ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 }; TCHAR defbuf[MAX_PATH],buf[MAX_PATH]; int param_count = 3; // Set up enum_token the way Invoke expects: enum_token.symbol = SYM_STRING; enum_token.marker = _T(""); enum_token.mem_to_free = NULL; enum_token.buf = defbuf; // Prepare to call object._NewEnum(): param_tokens[0].symbol = SYM_STRING; param_tokens[0].marker = _T("_NewEnum"); objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1); if (enum_token.mem_to_free) // Invoke returned memory for us to free. free(enum_token.mem_to_free); // Check if object returned an enumerator, otherwise return if (enum_token.symbol != SYM_OBJECT) return; // create variables to use in for loop / for enumeration // these will be deleted afterwards Var *var1 = (Var*)alloca(sizeof(Var)); Var *var2 = (Var*)alloca(sizeof(Var)); var1->mType = var2->mType = VAR_NORMAL; var1->mAttrib = var2->mAttrib = 0; var1->mByteCapacity = var2->mByteCapacity = 0; var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC; // Prepare parameters for the loop below: enum.Next(var1 [, var2]) param_tokens[0].marker = _T("Next"); param_tokens[1].symbol = SYM_VAR; param_tokens[1].var = var1; param_tokens[1].mem_to_free = 0; param_tokens[2].symbol = SYM_VAR; param_tokens[2].var = var2; param_tokens[2].mem_to_free = 0; ExprTokenType result_token; IObject &enumerator = *enum_token.object; // Might perform better as a reference? this_token.symbol = SYM_OBJECT; this_token.object = this; for (;;) { // Set up result_token the way Invoke expects; each Invoke() will change some or all of these: result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; // Call enumerator.Next(var1, var2) enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count); bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token)); if (!next_returned_true) break; this->Invoke(ResultToken,this_token,IT_SET,params+1,2); // release object if it was assigned prevoiously when calling enum.Next if (var1->IsObject()) var1->ReleaseObject(); if (var2->IsObject()) var2->ReleaseObject(); // Free any memory or object which may have been returned by Invoke: if (result_token.mem_to_free) free(result_token.mem_to_free); if (result_token.symbol == SYM_OBJECT) result_token.object->Release(); } // release enumerator and free vars enumerator.Release(); var1->Free(); var2->Free(); } // // Struct::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool Struct::Delete() { return ObjectBase::Delete(); } Struct::~Struct() { if (mMemAllocated > 0) free(mStructMem); if (mFields) { if (mFieldCount) { IndexType i = mFieldCount - 1; // Free keys for ( ; i >= 0 ; --i) { if (mFields[i].mMemAllocated > 0) free(mFields[i].mStructMem); free(mFields[i].key); } } // Free fields array. free(mFields); } } // // Struct::SetPointer - used to set pointer for a field or array item // UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem) { if (mIsPointer) *((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; else *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; return aPointer; } // // Struct::FieldType::Clone - used to clone a field to structure. // Struct *Struct::CloneField(FieldType *field,bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; // if field is an array, set correct size if (obj.mArraySize = field->mArraySize) obj.mSize = field->mSize*obj.mArraySize; else obj.mSize = field->mSize; obj.mIsInteger = field->mIsInteger; obj.mIsPointer = field->mIsPointer; obj.mEncoding = field->mEncoding; obj.mIsUnsigned = field->mIsUnsigned; obj.mVarRef = field->mVarRef; obj.mTypeOnly = 1; obj.mMemAllocated = aIsDynamic ? -1 : 0; return objptr; } // // Struct::Clone - used for cloning structures. // Struct *Struct::Clone(bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; obj.mArraySize = mArraySize; obj.mIsInteger = mIsInteger; obj.mIsPointer = mIsPointer; obj.mEncoding = mEncoding; obj.mIsUnsigned = mIsUnsigned; obj.mSize = mSize; obj.mVarRef = mVarRef; obj.mTypeOnly = mTypeOnly; // -1 will identify a dynamic structure, no memory can be allocated to such obj.mMemAllocated = aIsDynamic ? -1 : 0; // Allocate space in destination object. if (!obj.SetInternalCapacity(mFieldCount)) { obj.Release(); return NULL; } FieldType *fields = obj.mFields; // Newly allocated by above. int failure_count = 0; // See comment below. IndexType i; obj.mFieldCount = mFieldCount; for (i = 0; i < mFieldCount; ++i) { FieldType &dst = fields[i]; FieldType &src = mFields[i]; if ( !(dst.key = _tcsdup(src.key)) ) { // Key allocation failed. // Rather than trying to set up the object so that what we have // so far is valid in order to break out of the loop, continue, // make all fields valid and then allow them to be freed. ++failure_count; } dst.mArraySize = src.mArraySize; dst.mIsInteger = src.mIsInteger; dst.mIsPointer = src.mIsPointer; dst.mEncoding = src.mEncoding; dst.mIsUnsigned = src.mIsUnsigned; dst.mOffset = src.mOffset; dst.mSize = src.mSize; dst.mVarRef = src.mVarRef; dst.mMemAllocated = aIsDynamic ? -1 : 0; } if (failure_count) { // One or more memory allocations failed. It seems best to return a clear failure // indication rather than an incomplete copy. Now that the loop above has finished, // the object's contents are at least valid and it is safe to free the object: obj.Release(); return NULL; } return &obj; } // // Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object. // ResultType STDMETHODCALLTYPE Struct::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) // L40: Revised base mechanism for flexibility and to simplify some aspects. // obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc. { int ptrsize = sizeof(UINT_PTR); FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL ResultType Result = OK; // Used to resolve dynamic structures ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2},ResultToken; // used to clone a dynamic field or structure Struct *objclone = NULL; // used for StrGet/StrPut LPCVOID source_string; int source_length; DWORD flags = WC_NO_BEST_FIT_CHARS; int length = -1; int char_count; // Identify that we need to release/delete field or structure object bool deletefield = false; bool releaseobj = false; int param_count_excluding_rvalue = aParamCount; // target may be altered here to resolve dynamic structure so hold it separately UINT_PTR *target = mStructMem; if (IS_INVOKE_SET) { // Prior validation of ObjSet() param count ensures the result won't be negative: --param_count_excluding_rvalue; // Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best // to have it also block __Set. The code below is disabled to achieve this, with a slight cost to // performance when assigning to a new key in any object which has a base object. (The cost may // depend on how many key-value pairs each base object has.) Note that this doesn't affect meta- // functions defined in *this* base object, since they were already invoked if present. //if (IS_INVOKE_META) //{ // if (param_count_excluding_rvalue == 1) // // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to. // // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue. // param_count_excluding_rvalue = 0; // //else: Allow SET to operate on a field of an object stored in the target's base. // // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc. //} } if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0]))) { // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr if (IS_INVOKE_SET) { if (TokenToObject(*aParam[param_count_excluding_rvalue])) { // Initialize structure using an object. e.g. struct[]:={x:1,y:2} this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue])); // return struct object aResultToken.symbol = SYM_OBJECT; aResultToken.object = this; this->AddRef(); return OK; } if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer { free(mStructMem); mMemAllocated = 0; } // assign new pointer to structure // releasing/deleting structure will not free that memory mStructMem = (UINT_PTR *)TokenToInt64(*aParam[param_count_excluding_rvalue]); } // Return new structure address aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64)mStructMem; return OK; } else { // Array access, struct.1 or struct[1] or struct[1].x ... if (TokenIsPureNumeric(*aParam[0])) { if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1])) { // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) // simply set pointer aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0])); else { // resolve pointer to pointer and set it UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = ((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1))); else { // resolve pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } aResultToken.symbol = SYM_INTEGER; return OK; } // Structure is a reference to variable and not a pointer, get size of structure if (mVarRef && !mIsPointer) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // Variable is a structure object, copy size if (TokenToObject(Var2)) ResultToken.value_int64 = ((Struct *)TokenToObject(Var2))->mSize; else { // use sizeof to find out the size of structure param[0]->symbol = SYM_STRING; Var1.marker = TokenToString(*param[1]); BIF_sizeof(Result,ResultToken,param,1); } } // Check if we have an array, if structure is not array and not pointer, assume array if (mArraySize || !mIsPointer) // if not Array and not pointer assume it is an array target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mIsPointer ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize/(mArraySize ? mArraySize : 1)))); else if (mIsPointer) // resolve pointer target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0])-1)*ptrsize); else // amend target to memory of field target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mVarRef ? ResultToken.value_int64 : mSize)); // Structure has a variable reference and might be a pointer but not pointer to pointer if (mVarRef && mIsPointer < 2) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // variable is a structure object, clone it if (TokenToObject(Var2)) { objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target; if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } // Object to Structure if (IS_INVOKE_SET && TokenToObject(*aParam[1])) { objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // MULTIPARAM if (param_count_excluding_rvalue > 1) { objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; return OK; } else { Var1.symbol = SYM_STRING; Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = (UINT_PTR)target; if (objclone = Struct::Create(param,2)) { Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } tempobj->Release(); if (IS_INVOKE_SET && TokenToObject(*aParam[1])) { objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (param_count_excluding_rvalue > 1) { objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; }
tinku99/ahkdll
47620b8e90fa4025c0949ee6f3ccab972662901f
Fixed typedef declarations for CreateActCtx
diff --git a/source/MemoryModule.cpp b/source/MemoryModule.cpp index cfc8f70..650f688 100644 --- a/source/MemoryModule.cpp +++ b/source/MemoryModule.cpp @@ -1,581 +1,581 @@ /* * Memory DLL loading code * Version 0.0.2 * * Copyright (c) 2004-2011 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2011 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #include "stdafx.h" // pre-compiled headers #include "MemoryModule.h" #include "globaldata.h" // for access to many global vars #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif //#include <Windows.h> #include <winnt.h> //#include <stdio.h> //#ifdef DEBUG_OUTPUT //#include <stdio.h> //#endif #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif typedef struct { PIMAGE_NT_HEADERS headers; unsigned char *codeBase; HMODULE *modules; int numModules; int initialized; } MEMORYMODULE, *PMEMORYMODULE; typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); -typedef HANDLE (*MyCreateActCtx)(PACTCTXA); -typedef HANDLE (*MyDeactivateActCtx)(DWORD,ULONG_PTR); -typedef BOOL (*MyActivateActCtx)(HANDLE,ULONG_PTR*); +typedef HANDLE (WINAPI * MyCreateActCtx)(PACTCTXA); +typedef HANDLE (WINAPI * MyDeactivateActCtx)(DWORD,ULONG_PTR); +typedef BOOL (WINAPI * MyActivateActCtx)(HANDLE,ULONG_PTR*); HMODULE libkernel32 = LoadLibrary(_T("kernel32.dll")); MyCreateActCtx _CreateActCtxA = (MyCreateActCtx)GetProcAddress(libkernel32,"CreateActCtxA"); MyDeactivateActCtx _DeactivateActCtx = (MyDeactivateActCtx)GetProcAddress(libkernel32,"DeactivateActCtx"); MyActivateActCtx _ActivateActCtx = (MyActivateActCtx)GetProcAddress(libkernel32,"ActivateActCtx"); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen((const char*)tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugStringA(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_EXECUTE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_READWRITE}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) { #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page"); #endif break; } } } #ifndef _WIN64 #undef imageOffset #endif } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); #ifdef _WIN64 *patchAddrHL += (DWORD)delta; #else *patchAddrHL += delta; #endif break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result = 1; ULONG_PTR lpCookie = 0; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); PIMAGE_DATA_DIRECTORY resource = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_RESOURCE); if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); // Following will be used to resolve manifest in module if (resource->Size) { PIMAGE_RESOURCE_DIRECTORY resDir = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + resource->VirtualAddress); PIMAGE_RESOURCE_DIRECTORY resDirTemp; PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY)); PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntryTemp; PIMAGE_RESOURCE_DATA_ENTRY resDataEntry; // ACTCTX Structure, not used members must be set to 0! ACTCTXA actctx ={0,0,0,0,0,0,0,0,0}; actctx.cbSize = sizeof(actctx); HANDLE hActCtx; // Path to temp directory + our temporary file name CHAR buf[MAX_PATH]; DWORD tempPathLength = GetTempPathA(MAX_PATH, buf); memcpy(buf + tempPathLength,"AutoHotkey.MemoryModule.temp.manifest",38); actctx.lpSource = buf; // Enumerate Resources int i = 0; for (;i < resDir->NumberOfIdEntries + resDir->NumberOfNamedEntries;i++) { // Resolve current entry resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY) + (i*sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))); // If entry is directory and Id is 24 = RT_MANIFEST if (resDirEntry->DataIsDirectory && resDirEntry->Id == 24) { //resDirTemp = (PIMAGE_RESOURCE_DIRECTORY)((char*)resDir + (resDirEntry->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntry->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDirTemp = (PIMAGE_RESOURCE_DIRECTORY) ((char*)resDir + (resDirEntryTemp->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntryTemp->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDataEntry = (PIMAGE_RESOURCE_DATA_ENTRY) ((char*)resDir + (resDirEntryTemp->OffsetToData)); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after CreateActCtx has been called. HANDLE hFile = CreateFileA(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif break; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,(codeBase + resDataEntry->OffsetToData),resDataEntry->Size,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); #endif break; //failed to write data, continue and try loading } hActCtx = _CreateActCtxA(&actctx); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileA(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); if (hActCtx == INVALID_HANDLE_VALUE) break; //failed to create context, continue and try loading _ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway break; // Break since a dll can have only 1 manifest } } } for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle; #if DEBUG_OUTPUT OutputDebugStringA((LPCSTR) (codeBase + importDesc->Name)); #endif if (!(handle = LoadLibraryA((LPCSTR) (codeBase + importDesc->Name)))) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif result = 0; break; } #if DEBUG_OUTPUT #endif module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)IMAGE_ORDINAL(*thunkRef)); #endif } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)&thunkData->Name); #endif } if (*funcRef == 0) { result = 0; break; } } if (!result) { break; } } } if (lpCookie) _DeactivateActCtx(0,lpCookie); return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("Not a valid executable file.\n"); #endif return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("No PE header found.\n"); #endif return NULL; } // reserve memory for image of library code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { #if DEBUG_OUTPUT OutputLastError("Can't reserve memory"); #endif return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... VirtualAlloc(code, old_header->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // copy PE header to code memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections((const unsigned char*)data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { #if DEBUG_OUTPUT OutputDebugStringA("BuildImportTable failed.\n"); #endif goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugStringA("Library has no entry point.\n"); #endif goto error; } // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); if (!successfull) { #if DEBUG_OUTPUT OutputDebugStringA("Can't attach library.\n"); #endif goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod;
tinku99/ahkdll
01041354d2cfbd6c46b29561104c49d91c737b07
Fixed MemoryLibrary to support Win2000
diff --git a/source/MemoryModule.cpp b/source/MemoryModule.cpp index 4848f1e..cfc8f70 100644 --- a/source/MemoryModule.cpp +++ b/source/MemoryModule.cpp @@ -1,601 +1,609 @@ /* * Memory DLL loading code * Version 0.0.2 * * Copyright (c) 2004-2011 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2011 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #include "stdafx.h" // pre-compiled headers #include "MemoryModule.h" #include "globaldata.h" // for access to many global vars #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif //#include <Windows.h> #include <winnt.h> //#include <stdio.h> //#ifdef DEBUG_OUTPUT //#include <stdio.h> //#endif #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif typedef struct { PIMAGE_NT_HEADERS headers; unsigned char *codeBase; HMODULE *modules; int numModules; int initialized; } MEMORYMODULE, *PMEMORYMODULE; typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); +typedef HANDLE (*MyCreateActCtx)(PACTCTXA); +typedef HANDLE (*MyDeactivateActCtx)(DWORD,ULONG_PTR); +typedef BOOL (*MyActivateActCtx)(HANDLE,ULONG_PTR*); +HMODULE libkernel32 = LoadLibrary(_T("kernel32.dll")); +MyCreateActCtx _CreateActCtxA = (MyCreateActCtx)GetProcAddress(libkernel32,"CreateActCtxA"); +MyDeactivateActCtx _DeactivateActCtx = (MyDeactivateActCtx)GetProcAddress(libkernel32,"DeactivateActCtx"); +MyActivateActCtx _ActivateActCtx = (MyActivateActCtx)GetProcAddress(libkernel32,"ActivateActCtx"); + + #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen((const char*)tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugStringA(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_EXECUTE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_READWRITE}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif - // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } - + // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } - + if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) { #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page"); #endif break; } } } #ifndef _WIN64 #undef imageOffset #endif } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); #ifdef _WIN64 *patchAddrHL += (DWORD)delta; #else *patchAddrHL += delta; #endif break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result = 1; ULONG_PTR lpCookie = 0; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); PIMAGE_DATA_DIRECTORY resource = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_RESOURCE); + if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); // Following will be used to resolve manifest in module if (resource->Size) { PIMAGE_RESOURCE_DIRECTORY resDir = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + resource->VirtualAddress); PIMAGE_RESOURCE_DIRECTORY resDirTemp; PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY)); PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntryTemp; PIMAGE_RESOURCE_DATA_ENTRY resDataEntry; // ACTCTX Structure, not used members must be set to 0! ACTCTXA actctx ={0,0,0,0,0,0,0,0,0}; actctx.cbSize = sizeof(actctx); HANDLE hActCtx; // Path to temp directory + our temporary file name CHAR buf[MAX_PATH]; DWORD tempPathLength = GetTempPathA(MAX_PATH, buf); memcpy(buf + tempPathLength,"AutoHotkey.MemoryModule.temp.manifest",38); actctx.lpSource = buf; // Enumerate Resources int i = 0; for (;i < resDir->NumberOfIdEntries + resDir->NumberOfNamedEntries;i++) { // Resolve current entry resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY) + (i*sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))); // If entry is directory and Id is 24 = RT_MANIFEST if (resDirEntry->DataIsDirectory && resDirEntry->Id == 24) { //resDirTemp = (PIMAGE_RESOURCE_DIRECTORY)((char*)resDir + (resDirEntry->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntry->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDirTemp = (PIMAGE_RESOURCE_DIRECTORY) ((char*)resDir + (resDirEntryTemp->OffsetToDirectory)); resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntryTemp->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); resDataEntry = (PIMAGE_RESOURCE_DATA_ENTRY) ((char*)resDir + (resDirEntryTemp->OffsetToData)); // Write manifest to temportary file // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk // It will be deleted after CreateActCtx has been called. HANDLE hFile = CreateFileA(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); if (hFile == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputDebugStringA("CreateFile failed.\n"); #endif break; //failed to create file, continue and try loading without CreateActCtx } DWORD byteswritten = 0; WriteFile(hFile,(codeBase + resDataEntry->OffsetToData),resDataEntry->Size,&byteswritten,NULL); CloseHandle(hFile); if (byteswritten == 0) { -#if DEBUG_OUTPUT + #if DEBUG_OUTPUT OutputDebugStringA("WriteFile failed.\n"); -#endif + #endif break; //failed to write data, continue and try loading } - hActCtx = CreateActCtxA(&actctx); + hActCtx = _CreateActCtxA(&actctx); // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) hFile = CreateFileA(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); CloseHandle(hFile); if (hActCtx == INVALID_HANDLE_VALUE) break; //failed to create context, continue and try loading - ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway + _ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway break; // Break since a dll can have only 1 manifest } } } for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle; #if DEBUG_OUTPUT OutputDebugStringA((LPCSTR) (codeBase + importDesc->Name)); #endif if (!(handle = LoadLibraryA((LPCSTR) (codeBase + importDesc->Name)))) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif result = 0; break; } #if DEBUG_OUTPUT #endif module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)IMAGE_ORDINAL(*thunkRef)); #endif } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)&thunkData->Name); #endif } if (*funcRef == 0) { result = 0; break; } } if (!result) { break; } } } if (lpCookie) - DeactivateActCtx(0,lpCookie); + _DeactivateActCtx(0,lpCookie); return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("Not a valid executable file.\n"); #endif return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("No PE header found.\n"); #endif return NULL; } // reserve memory for image of library code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { #if DEBUG_OUTPUT OutputLastError("Can't reserve memory"); #endif return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... VirtualAlloc(code, old_header->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE); - + // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // copy PE header to code memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections((const unsigned char*)data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } - + // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { #if DEBUG_OUTPUT OutputDebugStringA("BuildImportTable failed.\n"); #endif goto error; } - // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugStringA("Library has no entry point.\n"); #endif goto error; } // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); if (!successfull) { #if DEBUG_OUTPUT OutputDebugStringA("Can't attach library.\n"); #endif goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module != NULL) { if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } if (module->modules != NULL) { // free previously opened libraries for (i=0; i<module->numModules; i++) { if (module->modules[i] != INVALID_HANDLE_VALUE) { FreeLibrary(module->modules[i]); } } free(module->modules); } if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); } HeapFree(GetProcessHeap(), 0, module); } }
tinku99/ahkdll
d3d88be686ea70ab5986f8775cdb6a7b5687726c
AHK_L merged, else continue2 and ahk_exe
diff --git a/source/script.cpp b/source/script.cpp index 0bad5f9..57cbaf7 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -11221,1024 +11221,1027 @@ void *Script::GetVarType(LPTSTR aVarName) if (!_tcscmp(lower, _T("autotrim"))) return BIV_AutoTrim; if (!_tcscmp(lower, _T("stringcasesense"))) return BIV_StringCaseSense; if (!_tcscmp(lower, _T("formatinteger"))) return BIV_FormatInteger; if (!_tcscmp(lower, _T("formatfloat"))) return BIV_FormatFloat; if (!_tcscmp(lower, _T("keydelay"))) return BIV_KeyDelay; if (!_tcscmp(lower, _T("windelay"))) return BIV_WinDelay; if (!_tcscmp(lower, _T("controldelay"))) return BIV_ControlDelay; if (!_tcscmp(lower, _T("mousedelay"))) return BIV_MouseDelay; if (!_tcscmp(lower, _T("defaultmousespeed"))) return BIV_DefaultMouseSpeed; if (!_tcscmp(lower, _T("ispaused"))) return BIV_IsPaused; if (!_tcscmp(lower, _T("iscritical"))) return BIV_IsCritical; if (!_tcscmp(lower, _T("fileencoding"))) return BIV_FileEncoding; if (!_tcscmp(lower, _T("regview"))) return BIV_RegView; #ifndef MINIDLL if (!_tcscmp(lower, _T("issuspended"))) return BIV_IsSuspended; if (!_tcscmp(lower, _T("iconhidden"))) return BIV_IconHidden; if (!_tcscmp(lower, _T("icontip"))) return BIV_IconTip; if (!_tcscmp(lower, _T("iconfile"))) return BIV_IconFile; if (!_tcscmp(lower, _T("iconnumber"))) return BIV_IconNumber; #endif if (!_tcscmp(lower, _T("exitreason"))) return BIV_ExitReason; if (!_tcscmp(lower, _T("ostype"))) return BIV_OSType; if (!_tcscmp(lower, _T("osversion"))) return BIV_OSVersion; if (!_tcscmp(lower, _T("is64bitos"))) return BIV_Is64bitOS; if (!_tcscmp(lower, _T("language"))) return BIV_Language; if ( !_tcscmp(lower, _T("computername")) || !_tcscmp(lower, _T("username"))) return BIV_UserName_ComputerName; if (!_tcscmp(lower, _T("windir"))) return BIV_WinDir; if (!_tcscmp(lower, _T("temp"))) return BIV_Temp; // Debatably should be A_TempDir, but brevity seemed more popular with users, perhaps for heavy uses of the temp folder. if (!_tcscmp(lower, _T("mydocuments"))) return BIV_MyDocuments; if ( !_tcscmp(lower, _T("programfiles")) || !_tcscmp(lower, _T("appdata")) || !_tcscmp(lower, _T("appdatacommon")) || !_tcscmp(lower, _T("desktop")) || !_tcscmp(lower, _T("desktopcommon")) || !_tcscmp(lower, _T("startmenu")) || !_tcscmp(lower, _T("startmenucommon")) || !_tcscmp(lower, _T("programs")) || !_tcscmp(lower, _T("programscommon")) || !_tcscmp(lower, _T("startup")) || !_tcscmp(lower, _T("startupcommon"))) return BIV_SpecialFolderPath; if (!_tcscmp(lower, _T("isadmin"))) return BIV_IsAdmin; if (!_tcscmp(lower, _T("cursor"))) return BIV_Cursor; if ( !_tcscmp(lower, _T("caretx")) || !_tcscmp(lower, _T("carety"))) return BIV_Caret; if ( !_tcscmp(lower, _T("screenwidth")) || !_tcscmp(lower, _T("screenheight"))) return BIV_ScreenWidth_Height; if (!_tcsncmp(lower, _T("ipaddress"), 9)) { lower += 9; return (*lower >= '1' && *lower <= '4' && !lower[1]) // Make sure has only one more character rather than none or several (e.g. A_IPAddress1abc should not be match). ? BIV_IPAddress : (void *)VAR_NORMAL; // Otherwise it can't be a match for any built-in variable. } if (!_tcsncmp(lower, _T("loop"), 4)) { lower += 4; if (!_tcscmp(lower, _T("readline"))) return BIV_LoopReadLine; if (!_tcscmp(lower, _T("field"))) return BIV_LoopField; if (!_tcsncmp(lower, _T("file"), 4)) { lower += 4; if (!_tcscmp(lower, _T("name"))) return BIV_LoopFileName; if (!_tcscmp(lower, _T("shortname"))) return BIV_LoopFileShortName; if (!_tcscmp(lower, _T("ext"))) return BIV_LoopFileExt; if (!_tcscmp(lower, _T("dir"))) return BIV_LoopFileDir; if (!_tcscmp(lower, _T("fullpath"))) return BIV_LoopFileFullPath; if (!_tcscmp(lower, _T("longpath"))) return BIV_LoopFileLongPath; if (!_tcscmp(lower, _T("shortpath"))) return BIV_LoopFileShortPath; if (!_tcscmp(lower, _T("attrib"))) return BIV_LoopFileAttrib; if ( !_tcscmp(lower, _T("timemodified")) || !_tcscmp(lower, _T("timecreated")) || !_tcscmp(lower, _T("timeaccessed"))) return BIV_LoopFileTime; if ( !_tcscmp(lower, _T("size")) || !_tcscmp(lower, _T("sizekb")) || !_tcscmp(lower, _T("sizemb"))) return BIV_LoopFileSize; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } if (!_tcsncmp(lower, _T("reg"), 3)) { lower += 3; if (!_tcscmp(lower, _T("type"))) return BIV_LoopRegType; if (!_tcscmp(lower, _T("key"))) return BIV_LoopRegKey; if (!_tcscmp(lower, _T("subkey"))) return BIV_LoopRegSubKey; if (!_tcscmp(lower, _T("name"))) return BIV_LoopRegName; if (!_tcscmp(lower, _T("timemodified"))) return BIV_LoopRegTimeModified; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } } if (!_tcscmp(lower, _T("thisfunc"))) return BIV_ThisFunc; if (!_tcscmp(lower, _T("thislabel"))) return BIV_ThisLabel; #ifndef MINIDLL if (!_tcscmp(lower, _T("thismenuitem"))) return BIV_ThisMenuItem; if (!_tcscmp(lower, _T("thismenuitempos"))) return BIV_ThisMenuItemPos; if (!_tcscmp(lower, _T("thismenu"))) return BIV_ThisMenu; if (!_tcscmp(lower, _T("thishotkey"))) return BIV_ThisHotkey; if (!_tcscmp(lower, _T("priorhotkey"))) return BIV_PriorHotkey; if (!_tcscmp(lower, _T("timesincethishotkey"))) return BIV_TimeSinceThisHotkey; if (!_tcscmp(lower, _T("timesincepriorhotkey"))) return BIV_TimeSincePriorHotkey; if (!_tcscmp(lower, _T("endchar"))) return BIV_EndChar; #endif if (!_tcscmp(lower, _T("lasterror"))) return BIV_LastError; if (!_tcscmp(lower, _T("globalstruct"))) return BIV_GlobalStruct; if (!_tcscmp(lower, _T("scriptstruct"))) return BIV_ScriptStruct; if (!_tcscmp(lower, _T("modulehandle"))) return BIV_ModuleHandle; if (!_tcscmp(lower, _T("isdll"))) return BIV_IsDll; if (!_tcsncmp(lower, _T("coordmode"), 9)) return BIV_CoordMode; if (!_tcscmp(lower, _T("eventinfo"))) return BIV_EventInfo; // It's called "EventInfo" vs. "GuiEventInfo" because it applies to non-Gui events such as OnClipboardChange. #ifndef MINIDLL if (!_tcscmp(lower, _T("guicontrol"))) return BIV_GuiControl; if ( !_tcscmp(lower, _T("guicontrolevent")) // v1.0.36: A_GuiEvent was added as a synonym for A_GuiControlEvent because it seems unlikely that A_GuiEvent will ever be needed for anything: || !_tcscmp(lower, _T("guievent"))) return BIV_GuiEvent; if ( !_tcscmp(lower, _T("gui")) || !_tcscmp(lower, _T("guiwidth")) || !_tcscmp(lower, _T("guiheight")) || !_tcscmp(lower, _T("guix")) // Naming: Brevity seems more a benefit than would A_GuiEventX's improved clarity. || !_tcscmp(lower, _T("guiy"))) return BIV_Gui; // These can be overloaded if a GuiMove label or similar is ever needed. if (!_tcscmp(lower, _T("priorkey"))) return BIV_PriorKey; #endif if (!_tcscmp(lower, _T("timeidle"))) return BIV_TimeIdle; if (!_tcscmp(lower, _T("timeidlephysical"))) return BIV_TimeIdlePhysical; if ( !_tcscmp(lower, _T("space")) || !_tcscmp(lower, _T("tab"))) return BIV_Space_Tab; if (!_tcscmp(lower, _T("ahkversion"))) return BIV_AhkVersion; if (!_tcscmp(lower, _T("ahkpath"))) return BIV_AhkPath; if (!_tcscmp(lower, _T("dllpath"))) return BIV_DllPath; // Since above didn't return: return (void *)VAR_NORMAL; } WinGroup *Script::FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound) // Caller must ensure that aGroupName isn't NULL. But if it's the empty string, NULL is returned. // Returns the Group whose name matches aGroupName. If it doesn't exist, it is created if aCreateIfNotFound==true. // Thread-safety: This function is thread-safe (except when called with aCreateIfNotFound==true) even when // the main thread happens to be calling AddGroup() and changing the linked list while it's being traversed here // by the hook thread. However, any subsequent changes to this function or AddGroup() must be carefully reviewed. { if (!*aGroupName) { if (aCreateIfNotFound) // An error message must be shown in this case since or caller is about to // exit the current script thread (and we don't want it to happen silently). ScriptError(_T("Blank group name.")); return NULL; } for (WinGroup *group = mFirstGroup; group != NULL; group = group->mNextGroup) if (!_tcsicmp(group->mName, aGroupName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return group; // Match found. // Otherwise, no match found, so create a new group. if (!aCreateIfNotFound || AddGroup(aGroupName) != OK) return NULL; return mLastGroup; } ResultType Script::AddGroup(LPTSTR aGroupName) // Returns OK or FAIL. // The caller must already have verified that this isn't a duplicate group. // This function is not thread-safe because it adds an entry to the quasi-global list of window groups. // In addition, if this function is being called by one thread while another thread is calling FindGroup(), // the thread-safety notes in FindGroup() apply. { size_t aGroupName_length = _tcslen(aGroupName); if (aGroupName_length > MAX_VAR_NAME_LENGTH) return ScriptError(_T("Group name too long."), aGroupName); if (!Var::ValidateName(aGroupName, DISPLAY_NO_ERROR)) // Seems best to use same validation as var names. return ScriptError(_T("Illegal group name."), aGroupName); LPTSTR new_name = SimpleHeap::Malloc(aGroupName, aGroupName_length); if (!new_name) return FAIL; // It already displayed the error for us. // The precise method by which the follows steps are done should be thread-safe even if // some other thread calls FindGroup() in the middle of the operation. But any changes // must be carefully reviewed: WinGroup *the_new_group = new WinGroup(new_name); if (the_new_group == NULL) return ScriptError(ERR_OUTOFMEM); if (mFirstGroup == NULL) mFirstGroup = the_new_group; else mLastGroup->mNextGroup = the_new_group; // This must be done after the above: mLastGroup = the_new_group; return OK; } Line *Script::PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd, Line *aParentLine) // aFindBlockEnd should be true, only when this function is called // by itself. The end of this function relies upon this definition. // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). { // Not thread-safe, so this can only parse one script at a time. // Not a problem for the foreseeable future: static int nest_level; // Level zero is the outermost one: outside all blocks. static bool abort; if (!aParentLine) { // We were called from outside, not recursively, so init these. This is // very important if this function is ever to be called from outside // more than once, even though it isn't currently: nest_level = 0; abort = false; } int i; DerefType *deref; // Don't check aStartingLine here at top: only do it at the bottom // for its differing return values. for (Line *line = aStartingLine; line;) { // Check if any of each arg's derefs are function calls. If so, do some validation and // preprocessing to set things up for better runtime performance: for (i = 0; i < line->mArgc; ++i) // For each arg. { ArgStruct &this_arg = line->mArg[i]; // For performance and convenience. // Exclude the derefs of output and input vars from consideration, since they can't // be function calls: if (!this_arg.is_expression) // For now, only expressions are capable of calling functions. If ever change this, might want to add a check here for this_arg.type != ARG_TYPE_NORMAL (for performance). continue; if (this_arg.deref) // No function-calls are present because the expression contains neither variables nor function calls. { for (deref = this_arg.deref; deref->marker; ++deref) // For each deref. { if (!deref->is_function) continue; if ( !(deref->func = FindFunc(deref->marker, deref->length)) ) { #ifndef AUTOHOTKEYSC bool error_was_shown, file_was_found; if ( !(deref->func = FindFuncInLibrary(deref->marker, deref->length, error_was_shown, file_was_found, true)) ) { abort = true; // So that the caller doesn't also report an error. // When above already displayed the proximate cause of the error, it's usually // undesirable to show the cascade effects of that error in a second dialog: return error_was_shown ? NULL : line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); } #else abort = true; return line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); #endif } // L31: Parameter counting and validation was previously done in this section, // but is now handled by ExpressionToPostfix. } // for each deref of this arg } // if (this_arg.deref) if (!line->ExpressionToPostfix(this_arg)) // At this stage, this_arg.is_expression is known to be true. Doing this here, after the script has been loaded, might improve the compactness/adjacent-ness of the compiled expressions in memory, which might improve performance due to CPU caching. { abort = true; // So that the caller doesn't also report an error. return NULL; // The function above already displayed the error msg. } } // for each arg of this line // All lines in our recursion layer are assigned to the block that the caller specified: if (line->mParentLine == NULL) // i.e. don't do it if it's already "owned" by an IF or ELSE. line->mParentLine = aParentLine; // Can be NULL. if (ACT_IS_IF_OR_ELSE_OR_LOOP(line->mActionType) || line->mActionType == ACT_REPEAT) { // In this case, the loader should have already ensured that line->mNextLine is not NULL. if (line->mNextLine->mActionType == ACT_BLOCK_BEGIN && line->mNextLine->mAttribute == ATTR_TRUE) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Improper line below this.")); // Short message since so rare. A function must not be defined directly below an IF/ELSE/LOOP because runtime evaluation won't handle it properly. } if (line->mActionType == ACT_FOR) { ASSERT(line->mArgc == 3); // Now that this FOR's expression has been pre-parsed, exclude it from mArgc so that ExpandArgs() // won't evaluate it -- PerformLoopFor() needs to call ExpandExpression() directly in order to // receive the object reference which is the result of the expression. line->mArgc--; } // Make the line immediately following each ELSE, IF or LOOP be enclosed by that stmt. // This is done to make it illegal for a Goto or Gosub to jump into a deeper layer, // such as in this example: // #y:: // ifwinexist, pad // { // goto, label1 // ifwinexist, pad // label1: // ; With or without the enclosing block, the goto would still go to an illegal place // ; in the below, resulting in an "unexpected else" error: // { // msgbox, ifaction // } ; not necessary to make this line enclosed by the if because labels can't point to it? // else // msgbox, elseaction // } // return line->mNextLine->mParentLine = line; // Go onto the IF's or ELSE's action in case it too is an IF, rather than skipping over it: line = line->mNextLine; continue; } switch (line->mActionType) { case ACT_BLOCK_BEGIN: // Some insane limit too large to ever likely be exceeded, yet small enough not // to be a risk of stack overflow when recursing in ExecUntil(). Mostly, this is // here to reduce the chance of a program crash if a binary file, a corrupted file, // or something unexpected has been loaded as a script when it shouldn't have been. // Update: Increased the limit from 100 to 1000 so that large "else if" ladders // can be constructed. Going much larger than 1000 seems unwise since ExecUntil() // will have to recurse for each nest-level, possibly resulting in stack overflow // if things get too deep: if (nest_level > 1000) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Nesting too deep.")); // Short msg since so rare. } // Since the current convention is to store the line *after* the // BLOCK_END as the BLOCK_BEGIN's related line, that line can // be legitimately NULL if this block's BLOCK_END is the last // line in the script. So it's up to the called function // to report an error if it never finds a BLOCK_END for us. // UPDATE: The design requires that we do it here instead: ++nest_level; if (NULL == (line->mRelatedLine = PreparseBlocks(line->mNextLine, 1, line))) if (abort) // the above call already reported the error. return NULL; else { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(ERR_MISSING_CLOSE_BRACE); } --nest_level; // The convention is to have the BLOCK_BEGIN's related_line // point to the line *after* the BLOCK_END. line->mRelatedLine = line->mRelatedLine->mNextLine; // Might be NULL now. // Otherwise, since any blocks contained inside this one would already // have been handled by the recursion in the above call, continue searching // from the end of this block: line = line->mRelatedLine; // If NULL, the loop-condition will catch it. break; case ACT_BLOCK_END: // Return NULL (failure) if the end was found but we weren't looking for one // (i.e. it's an orphan). Otherwise return the line after the block_end line, // which will become the caller's mRelatedLine. UPDATE: Return the // END_BLOCK line itself so that the caller can differentiate between // a NULL due to end-of-script and a NULL caused by an error: return aFindBlockEnd ? line // Doesn't seem necessary to set abort to true. : line->PreparseError(ERR_MISSING_OPEN_BRACE); default: // Continue line-by-line. line = line->mNextLine; } // switch() } // for each line // End of script has been reached. <line> is now NULL so don't attempt to dereference it. // If we were still looking for an EndBlock to match up with a begin, that's an error. // Don't report the error here because we don't know which begin-block is waiting // for an end (the caller knows and must report the error). UPDATE: Must report // the error here (see comments further above for explanation). UPDATE #2: Changed // it again: Now we let the caller handle it again: if (aFindBlockEnd) //return mLastLine->PreparseError("The script ends while a block is still open (missing })."); return NULL; // If no error, return something non-NULL to indicate success to the top-level caller. // We know we're returning to the top-level caller because aFindBlockEnd is only true // when we're recursed, and in that case the above would have returned. Thus, // we're not recursed upon reaching this line: return mLastLine; } Line *Script::PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode, AttributeType aLoopType) // Zero is the default for aMode, otherwise: // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). // Note: This function should be called with aMode == ONLY_ONE_LINE // only when aStartingLine's ActionType is something recursable such // as IF and BEGIN_BLOCK. Otherwise, it won't return after only one line. { static BOOL sInFunctionBody = FALSE; // Improves loadtime performance by allowing IsOutsideAnyFunctionBody() to be called only when necessary. // Don't check aStartingLine here at top: only do it at the bottom // for it's differing return values. Line *line_temp; AttributeType loop_type = aLoopType; for (Line *line = aStartingLine; line != NULL;) { if ( ACT_IS_IF(line->mActionType) || line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_REPEAT || line->mActionType == ACT_TRY ) { // ActionType is an IF or a LOOP or a TRY. line_temp = line->mNextLine; // line_temp is now this IF's or LOOP's or TRY's action-line. // Update: Below is commented out because it's now impossible (since all scripts end in ACT_EXIT): //if (line_temp == NULL) // This is an orphan IF/LOOP (has no action-line) at the end of the script. // return line->PreparseError(_T("Q")); // Placeholder. Formerly "This if-statement or loop has no action." // Other things rely on this check having been done, such as "if (line->mRelatedLine != NULL)": if (line_temp->mActionType == ACT_ELSE || line_temp->mActionType == ACT_BLOCK_END || line_temp->mActionType == ACT_CATCH) return line->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Lexikos: This section once maintained separate variables for file-pattern, registry, file-reading // and parsing loops. The intention seemed to be to validate certain commands such as FileAppend // differently depending on whether they're contained within a qualifying type of loop (even if some // other type of loop lies in between). However, that validation apparently wasn't implemented, // and implementing it now seems unnecessary. Doing so would also remove a useful capability: // // Loop, Read, %InputFile%, %OutputFile% // { // MyFunc(A_LoopReadLine) // } // MyFunc(line) { // ... do some processing on %line% ... // FileAppend, %line% ; This line could be considered an error, though it works in practice. // } // // Check if the IF's action-line is something we want to recurse. UPDATE: Always // recurse because other line types, such as Goto and Gosub, need to be preparsed // by this function even if they are the single-line actions of an IF or an ELSE. // Recurse this line rather than the next because we want the called function to // recurse again if this line is a ACT_BLOCK_BEGIN or is itself an IF. line_temp = PreparseIfElse(line_temp, ONLY_ONE_LINE, line->mAttribute ? line->mAttribute : loop_type); // If not end-of-script or error, line_temp is now either: // 1) If this if's/loop's action was a BEGIN_BLOCK: The line after the end of the block. // 2) If this if's/loop's action was another IF or LOOP: // a) the line after that if's else's action; or (if it doesn't have one): // b) the line after that if's/loop's action // 3) If this if's/loop's action was some single-line action: the line after that action. // In all of the above cases, line_temp is now the line where we // would expect to find an ELSE for this IF, if it has one. // Now the above has ensured that line_temp is this line's else, if it has one. // Note: line_temp will be NULL if the end of the script has been reached. // UPDATE: That can't happen now because all scripts end in ACT_EXIT: if (line_temp == NULL) // Error or end-of-script was reached. return NULL; // Seems best to keep this check for maintainability because changes to other checks can impact // whether this check will ever be "true": if (line->mRelatedLine != NULL) return line->PreparseError(_T("Q")); // Placeholder since it shouldn't happen. Formerly "This if-statement or LOOP unexpectedly already had an ELSE or end-point." // Set it to the else's action, rather than the else itself, since the else itself // is never needed during execution. UPDATE: No, instead set it to the ELSE itself // (if it has one) since we jump here at runtime when the IF is finished (whether // it's condition was true or false), thus skipping over any nested IF's that // aren't in blocks beneath it. If there's no ELSE, the below value serves as // the jumppoint we go to when the if-statement is finished. Example: // if x // if y // if z // action1 // else // action2 // action3 // x's jumppoint should be action3 so that all the nested if's // under the first one can be skipped after the "if x" line is recursively // evaluated. Because of this behavior, all IFs will have a related line // with the possibly exception of the very last if-statement in the script // (which is possible only if the script doesn't end in a Return or Exit). line->mRelatedLine = line_temp; // Even if <line> is a LOOP and line_temp and else? // Even if aMode == ONLY_ONE_LINE, an IF and its ELSE count as a single // statement (one line) due to its very nature (at least for this purpose), // so always continue on to evaluate the IF's ELSE, if present: if (line_temp->mActionType == ACT_ELSE) { if (line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_TRY || line->mActionType == ACT_REPEAT) { // this can't be our else, so let the caller handle it. if (aMode != ONLY_ONE_LINE) // This ELSE was encountered while sequentially scanning the contents // of a block or at the outermost nesting layer. More thought is required // to verify this is correct. UPDATE: This check is very old and I haven't // found a case that can produce it yet, but until proven otherwise its safer // to assume it's possible. return line_temp->PreparseError(ERR_ELSE_WITH_NO_IF); // Let the caller handle this else, since it can't be ours: return line_temp; } + // Fix for v1.1.09: Correct the line hierarchy for ELSE nested in an IF/ELSE/LOOP + // without braces. This is needed for named loops and perhaps other things. + line_temp->mParentLine = line->mParentLine; // Now use line vs. line_temp to hold the new values, so that line_temp // stays as a marker to the ELSE line itself: line = line_temp->mNextLine; // Set it to the else's action line. // Update: The following is now impossible because all scripts end in ACT_EXIT. // Thus, it's commented out: //if (line == NULL) // An else with no action. // return line_temp->PreparseError(_T("Q")); // Placeholder since impossible. Formerly "This ELSE has no action." if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this ELSE's jumppoint. This is similar to the jumppoint set for // an ELSEless IF, so see related comments above: line_temp->mRelatedLine = line; } else if (line_temp->mActionType == ACT_UNTIL) { if (line->mActionType != ACT_LOOP && line->mActionType != ACT_FOR) // Doesn't seem useful to allow it with WHILE? { // This is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_UNTIL_WITH_NO_LOOP); return line_temp; } // Continue processing *after* UNTIL. line = line_temp->mNextLine; } else if (line_temp->mActionType == ACT_CATCH) { if (line->mActionType != ACT_TRY) { // Again, this is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_CATCH_WITH_NO_TRY); return line_temp; } line = line_temp->mNextLine; if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this CATCH's jumppoint. line_temp->mRelatedLine = line; } else // line doesn't have an else, so just continue processing from line_temp's position line = line_temp; // Both cases above have ensured that line is now the first line beyond the // scope of the if-statement and that of any ELSE it may have. if (aMode == ONLY_ONE_LINE) // Return the next unprocessed line to the caller. return line; // Otherwise, continue processing at line's new location: continue; } // ActionType is "IF". // Since above didn't continue, do the switch: LPTSTR line_raw_arg1 = LINE_RAW_ARG1; // Resolve only once to help reduce code size. LPTSTR line_raw_arg2 = LINE_RAW_ARG2; // switch (line->mActionType) { case ACT_BLOCK_BEGIN: if (line->mAttribute == ATTR_TRUE) // This is the opening brace of a function definition. sInFunctionBody = TRUE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. line = PreparseIfElse(line->mNextLine, UNTIL_BLOCK_END, aLoopType); // "line" is now either NULL due to an error, or the location of the END_BLOCK itself. if (line == NULL) return NULL; // Error. break; case ACT_BLOCK_END: if (line->mAttribute == ATTR_TRUE) // This is the closing brace of a function definition. sInFunctionBody = FALSE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. if (aMode == ONLY_ONE_LINE) // Syntax error. The caller would never expect this single-line to be an // end-block. UPDATE: I think this is impossible because callers only use // aMode == ONLY_ONE_LINE when aStartingLine's ActionType is already // known to be an IF or a BLOCK_BEGIN: return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (single)." if (UNTIL_BLOCK_END) // Return line rather than line->mNextLine because, if we're at the end of // the script, it's up to the caller to differentiate between that condition // and the condition where NULL is an error indicator. return line; // Otherwise, we found an end-block we weren't looking for. This should be // impossible since the block pre-parsing already balanced all the blocks? return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (multi)." case ACT_BREAK: case ACT_CONTINUE: if (!aLoopType) return line->PreparseError(_T("Break/Continue must be enclosed by a Loop.")); if (line->mArgc) { if (line->ArgHasDeref(1) || line->mArg->is_expression) // It seems unlikely that computing the target loop at runtime would be useful. // For simplicity, rule out things like "break %var%" and "break % func()": return line->PreparseError(ERR_PARAM1_INVALID); //_T("Target label of Break/Continue cannot be dynamic.")); LPTSTR loop_name = line->mArg[0].text; Label *loop_label; Line *loop_line; if (IsPureNumeric(loop_name)) { int n = _ttoi(loop_name); // Find the nth innermost loop which encloses this line: for (loop_line = line->mParentLine; loop_line; loop_line = loop_line->mParentLine) if (loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) // i.e. LOOP, FOR or WHILE. if (--n < 1) break; if (!loop_line || n != 0) return line->PreparseError(ERR_PARAM1_INVALID); } else { // Target is a named loop. if ( !(loop_label = FindLabel(loop_name)) ) return line->PreparseError(ERR_NO_LABEL, loop_name); loop_line = loop_label->mJumpToLine; // Ensure the label points to a Loop, For-loop or While-loop ... if ( !(loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) // ... which encloses this line. Use line->mParentLine as the starting-point of // the "jump" to ensure the target isn't at the same nesting level as this line: || !line->mParentLine->IsJumpValid(*loop_label, true) ) return line->PreparseError(ERR_PARAM1_INVALID); //_T("Target label does not point to an appropriate Loop.")); // Although we've validated that it points to a loop, we can't resolve the line // after the loop's body as that (mRelatedLine) hasn't been determined yet. if (loop_line == line->mParentLine // line->mParentLine must be non-NULL because above verified this line is enclosed by a Loop: || line->mParentLine->mActionType == ACT_BLOCK_BEGIN && loop_line == line->mParentLine->mParentLine) { // Set mRelatedLine to NULL since the target loop directly encloses this line. loop_line = NULL; } } line->mRelatedLine = loop_line; } break; case ACT_GOSUB: // These two must be done here (i.e. *after* all the script lines have been added), case ACT_GOTO: // so that labels both above and below each Gosub/Goto can be resolved. if (line->ArgHasDeref(1)) // Since the jump-point contains a deref, it must be resolved at runtime: line->mRelatedLine = NULL; else { if (!line->GetJumpTarget(false)) return NULL; // Error was already displayed by called function. if (sInFunctionBody && ((Label *)(line->mRelatedLine))->mJumpToLine->IsOutsideAnyFunctionBody()) // Relies on above call to GetJumpTarget() having set line->mRelatedLine. { if (line->mActionType == ACT_GOTO) return line->PreparseError(_T("A Goto cannot jump from inside a function to outside.")); // Since this Gosub and its target line are both inside a function, they must both // be in the same function because otherwise GetJumpTarget() would have reported // the target as invalid. line->mAttribute = ATTR_TRUE; // v1.0.48.02: To improve runtime performance, mark this Gosub as having a target that is outside of any function body. } //else leave mAttribute at its line-constructor default of ATTR_NONE. } break; // These next 4 must also be done here (i.e. *after* all the script lines have been added), // so that labels both above and below this line can be resolved: case ACT_ONEXIT: if (*line_raw_arg1 && !line->ArgHasDeref(1)) if ( !(line->mAttribute = FindLabel(line_raw_arg1)) ) return line->PreparseError(ERR_NO_LABEL); break; case ACT_HOTKEY: #ifndef MINIDLL if (!line->ArgHasDeref(1)) { if (!_tcsnicmp(line_raw_arg1, _T("If"), 2)) { LPTSTR cp = line_raw_arg1 + 2; if (!*cp) // Just "If" { if (*line_raw_arg2 && !line->ArgHasDeref(2)) { // Hotkey, If, Expression: Ensure the expression matches exactly an existing #If, // as required by the Hotkey command. This seems worth doing since the current // behaviour might be unexpected (despite being documented), and because typos // are likely due to the fact that case and whitespace matter. int i; for (i = 0; i < g_HotExprLineCount; ++i) if (!_tcscmp(line_raw_arg2, g_HotExprLines[i]->mArg[0].text)) break; if (i == g_HotExprLineCount) return line->PreparseError(_T("Parameter #2 must match an existing #If expression.")); } break; } if (!_tcsnicmp(cp, _T("Win"), 3)) { cp += 3; if (!_tcsnicmp(cp, _T("Not"), 3)) cp += 3; if (!_tcsicmp(cp, _T("Active")) || !_tcsicmp(cp, _T("Exist"))) break; } // Since above didn't break, it's something invalid starting with "If". return line->PreparseError(ERR_PARAM1_INVALID); } if (*line_raw_arg2 && !line->ArgHasDeref(2)) if ( !(line->mAttribute = FindLabel(line_raw_arg2)) ) if (!Hotkey::ConvertAltTab(line_raw_arg2, true)) return line->PreparseError(ERR_NO_LABEL); } #endif break; case ACT_SETTIMER: if (*line_raw_arg1 && !line->ArgHasDeref(1)) if ( !(line->mAttribute = FindLabel(line_raw_arg1)) ) return line->PreparseError(ERR_NO_LABEL); if (*line_raw_arg2 && !line->ArgHasDeref(2)) if (!Line::ConvertOnOff(line_raw_arg2) && !IsPureNumeric(line_raw_arg2, true) // v1.0.46.16: Allow negatives to support the new run-only-once mode. && !line->mArg[1].is_expression) // v1.0.46.10: Don't consider expressions THAT CONTAIN NO VARIABLES OR FUNCTION-CALLS like "% 2*500" to be a syntax error. return line->PreparseError(ERR_PARAM2_INVALID); break; case ACT_GROUPADD: // This must be done here because it relies on all other lines already having been added. if (*LINE_RAW_ARG4 && !line->ArgHasDeref(4)) { // If the label name was contained in a variable, that label is now resolved and cannot // be changed. This is in contrast to something like "Gosub, %MyLabel%" where a change in // the value of MyLabel will change the behavior of the Gosub at runtime: Label *label = FindLabel(LINE_RAW_ARG4); if (!label) return line->PreparseError(ERR_NO_LABEL); line->mRelatedLine = (Line *)label; // The script loader has ensured that this can't be NULL. // Can't do this because the current line won't be the launching point for the // Gosub. Instead, the launching point will be the GroupActivate rather than the // GroupAdd, so it will be checked by the GroupActivate or not at all (since it's // not that important in the case of a Gosub -- it's mostly for Goto's): //return IsJumpValid(label->mJumpToLine); } break; case ACT_ELSE: // Should never happen because the part that handles the if's, above, should find // all the elses and handle them. UPDATE: This happens if there's // an extra ELSE in this scope level that has no IF: return line->PreparseError(ERR_ELSE_WITH_NO_IF); case ACT_UNTIL: // Similar to above. return line->PreparseError(ERR_UNTIL_WITH_NO_LOOP); case ACT_CATCH: // Similar to above. return line->PreparseError(ERR_CATCH_WITH_NO_TRY); } // switch() line = line->mNextLine; // If NULL due to physical end-of-script, the for-loop's condition will catch it. if (aMode == ONLY_ONE_LINE) // Return the next unprocessed line to the caller. // In this case, line shouldn't be (and probably can't be?) NULL because the line after // a single-line action shouldn't be the physical end of the script. That's because // the loader has ensured that all scripts now end in ACT_EXIT. And that final // ACT_EXIT should never be parsed here in ONLY_ONE_LINE mode because the only time // that mode is used is for the action of an IF, an ELSE, or possibly a LOOP. // In all of those cases, the final ACT_EXIT line in the script (which is explicitly // inserted by the loader) cannot be the line that was just processed by the // switch(). Therefore, the above assignment should not have set line to NULL // (which is good because NULL would probably be construed as "failure" by our // caller in this case): return line; // else just continue the for-loop at the new value of line. } // for() // End of script has been reached. line is now NULL so don't dereference it. // If we were still looking for an EndBlock to match up with a begin, that's an error. // This indicates that the at least one BLOCK_BEGIN is missing a BLOCK_END. // However, since the blocks were already balanced by the block pre-parsing function, // this should be impossible unless the design of this function is flawed. if (aMode == UNTIL_BLOCK_END) #ifdef _DEBUG return mLastLine->PreparseError(_T("DEBUG: The script ended while a block was still open.")); // This is a bug because the preparser already verified all blocks are balanced. #else return NULL; // Shouldn't happen, so just return failure. #endif // If we were told to process a single line, we were recursed and it should have returned above, // so it's an error here (can happen if we were called with aStartingLine == NULL?): if (aMode == ONLY_ONE_LINE) return mLastLine->PreparseError(_T("Q")); // Placeholder since probably impossible. Formerly "The script ended while an action was still expected." // Otherwise, return something non-NULL to indicate success to the top-level caller: return mLastLine; } ResultType Line::ExpressionToPostfix(ArgStruct &aArg) // Returns OK or FAIL. { // Having a precedence array is required at least for SYM_POWER (since the order of evaluation // of something like 2**1**2 does matter). It also helps performance by avoiding unnecessary pushing // and popping of operators to the stack. This array must be kept in sync with "enum SymbolType". // Also, dimensioning explicitly by SYM_COUNT helps enforce that at compile-time: static UCHAR sPrecedence[SYM_COUNT] = // Performance: UCHAR vs. INT benches a little faster, perhaps due to the slight reduction in code size it causes. { 0,0,0,0,0,0,0,0 // SYM_STRING, SYM_INTEGER, SYM_FLOAT, SYM_VAR, SYM_OPERAND, SYM_OBJECT, SYM_DYNAMIC, SYM_BEGIN (SYM_BEGIN must be lowest precedence). , 82, 82 // SYM_POST_INCREMENT, SYM_POST_DECREMENT: Highest precedence operator so that it will work even though it comes *after* a variable name (unlike other unaries, which come before). , 86 // SYM_DOT , 4,4,4,4,4,4 // SYM_CPAREN, SYM_CBRACKET, SYM_CBRACE, SYM_OPAREN, SYM_OBRACKET, SYM_OBRACE (to simplify the code, parentheses/brackets/braces must be lower than all operators in precedence). , 6 // SYM_COMMA -- Must be just above SYM_OPAREN so it doesn't pop OPARENs off the stack. , 7,7,7,7,7,7,7,7,7,7,7,7 // SYM_ASSIGN_*. THESE HAVE AN ODD NUMBER to indicate right-to-left evaluation order, which is necessary for cascading assignments such as x:=y:=1 to work. // , 8 // THIS VALUE MUST BE LEFT UNUSED so that the one above can be promoted to it by the infix-to-postfix routine. , 11, 11 // SYM_IFF_ELSE, SYM_IFF_THEN (ternary conditional). HAS AN ODD NUMBER to indicate right-to-left evaluation order, which is necessary for ternaries to perform traditionally when nested in each other without parentheses. // , 12 // THIS VALUE MUST BE LEFT UNUSED so that the one above can be promoted to it by the infix-to-postfix routine. , 16 // SYM_OR , 20 // SYM_AND , 25 // SYM_LOWNOT (the word "NOT": the low precedence version of logical-not). HAS AN ODD NUMBER to indicate right-to-left evaluation order so that things like "not not var" are supports (which can be used to convert a variable into a pure 1/0 boolean value). // , 26 // THIS VALUE MUST BE LEFT UNUSED so that the one above can be promoted to it by the infix-to-postfix routine. , 30, 30, 30 // SYM_EQUAL, SYM_EQUALCASE, SYM_NOTEQUAL (lower prec. than the below so that "x < 5 = var" means "result of comparison is the boolean value in var". , 34, 34, 34, 34 // SYM_GT, SYM_LT, SYM_GTOE, SYM_LTOE , 38 // SYM_CONCAT , 42 // SYM_BITOR -- Seems more intuitive to have these three higher in prec. than the above, unlike C and Perl, but like Python. , 46 // SYM_BITXOR , 50 // SYM_BITAND , 54, 54 // SYM_BITSHIFTLEFT, SYM_BITSHIFTRIGHT , 58, 58 // SYM_ADD, SYM_SUBTRACT , 62, 62, 62 // SYM_MULTIPLY, SYM_DIVIDE, SYM_FLOORDIVIDE , 67,67,67,67,67 // SYM_NEGATIVE (unary minus), SYM_HIGHNOT (the high precedence "!" operator), SYM_BITNOT, SYM_ADDRESS, SYM_DEREF // NOTE: THE ABOVE MUST BE AN ODD NUMBER to indicate right-to-left evaluation order, which was added in v1.0.46 to support consecutive unary operators such as !*var !!var (!!var can be used to convert a value into a pure 1/0 boolean). // , 68 // THIS VALUE MUST BE LEFT UNUSED so that the one above can be promoted to it by the infix-to-postfix routine. , 72 // SYM_POWER (see note below). Associativity kept as left-to-right for backward compatibility (e.g. 2**2**3 is 4**3=64 not 2**8=256). , 77, 77 // SYM_PRE_INCREMENT, SYM_PRE_DECREMENT (higher precedence than SYM_POWER because it doesn't make sense to evaluate power first because that would cause ++/-- to fail due to operating on a non-lvalue. // , 78 // THIS VALUE MUST BE LEFT UNUSED so that the one above can be promoted to it by the infix-to-postfix routine. // , 82, 82 // RESERVED FOR SYM_POST_INCREMENT, SYM_POST_DECREMENT (which are listed higher above for the performance of YIELDS_AN_OPERAND(). , 86 // SYM_FUNC -- Has special handling which ensures it stays tightly bound with its parameters as though it's a single operand for use by other operators; the actual value here is irrelevant. , 86 // SYM_NEW -- should be popped off the stack immediately after the pseudo function-call which follows it. , 36 // SYM_REGEXMATCH }; // Most programming languages give exponentiation a higher precedence than unary minus and logical-not. // For example, -2**2 is evaluated as -(2**2), not (-2)**2 (the latter is unsupported by qmathPow anyway). // However, this rule requires a small workaround in the postfix-builder to allow 2**-2 to be // evaluated as 2**(-2) rather than being seen as an error. v1.0.45: A similar thing is required // to allow the following to work: 2**!1, 2**not 0, 2**~0xFFFFFFFE, 2**&x. // On a related note, the right-to-left tradition of something like 2**3**4 is not implemented (maybe in v2). // Instead, the expression is evaluated from left-to-right (like other operators) to simplify the code. ExprTokenType infix[MAX_TOKENS], *postfix[MAX_TOKENS], *stack[MAX_TOKENS + 1]; // +1 for SYM_BEGIN on the stack. int infix_count = 0, postfix_count = 0, stack_count = 0; // Above dimensions the stack to be as large as the infix/postfix arrays to cover worst-case // scenarios and avoid having to check for overflow. For the infix-to-postfix conversion, the // stack must be large enough to hold a malformed expression consisting entirely of operators // (though other checks might prevent this). It must also be large enough for use by the final // expression evaluation phase, the worst case of which is unknown but certainly not larger // than MAX_TOKENS. /////////////////////////////////////////////////////////////////////////////////////////////// // TOKENIZE THE INFIX EXPRESSION INTO AN INFIX ARRAY: Avoids the performance overhead of having // to re-detect whether each symbol is an operand vs. operator at multiple stages. /////////////////////////////////////////////////////////////////////////////////////////////// // In v1.0.46.01, this section was simplified to avoid transcribing the entire expression into the // deref buffer. In addition to improving performance and reducing code size, this also solves // obscure timing bugs caused by functions that have side-effects, especially in comma-separated // sub-expressions. In these cases, one part of an expression could change a built-in variable // (indirectly or in the case of Clipboard, directly), an environment variable, or a double-def. // For example the dynamic components of a double-deref can be changed by other parts of an // expression, even one without commas. Another example is: fn(clipboard, func_that_changes_clip()). // So now, built-in & environment variables and double-derefs are resolve when they're actually // encountered during the final/evaluation phase. // Another benefit to deferring the resolution of these types of items is that they become eligible // for short-circuiting, which further helps performance (they're quite similar to built-in // functions in this respect). LPTSTR op_end, cp; DerefType *deref, *this_deref, *deref_start, *deref_new; int derefs_in_this_double; int cp1; // int vs. char benchmarks slightly faster, and is slightly smaller in code size. for (cp = aArg.text, deref = aArg.deref // Start at the beginning of this arg's text and look for the next deref. ;; ++deref, ++infix_count) // FOR EACH DEREF IN AN ARG: { this_deref = deref && deref->marker ? deref : NULL; // A deref with a NULL marker terminates the list (i.e. the final deref isn't a deref, merely a terminator of sorts. // BEFORE PROCESSING "this_deref" ITSELF, MUST FIRST PROCESS ANY LITERAL/RAW TEXT THAT LIES TO ITS LEFT. if (this_deref && cp < this_deref->marker // There's literal/raw text to the left of the next deref. || !this_deref && *cp) // ...or there's no next deref, but there's some literal raw text remaining to be processed. { for (;; ++infix_count) // FOR EACH TOKEN INSIDE THIS RAW/LITERAL TEXT SECTION. { // Because neither the postfix array nor the stack can ever wind up with more tokens than were // contained in the original infix array, only the infix array need be checked for overflow: if (infix_count > MAX_TOKENS - 1) // No room for this operator or operand to be added. return LineError(ERR_EXPR_TOO_LONG); // Only spaces and tabs are considered whitespace, leaving newlines and other whitespace characters // for possible future use: cp = omit_leading_whitespace(cp); if (!*cp // Very end of expression... || this_deref && cp >= this_deref->marker) // ...or no more literal/raw text left to process at the left side of this_deref. break; // Break out of inner loop so that bottom of the outer loop will process this_deref itself. ExprTokenType &this_infix_item = infix[infix_count]; // Might help reduce code size since it's referenced many places below. this_infix_item.deref = NULL; // Init needed for SYM_ASSIGN and related; a non-NULL deref means it should be converted to an object-assignment. // CHECK IF THIS CHARACTER IS AN OPERATOR. cp1 = cp[1]; // Improves performance by nearly 5% and appreciably reduces code size (at the expense of being less maintainable). switch (*cp) { // The most common cases are kept up top to enhance performance if switch() is implemented as if-else ladder. case '+': if (cp1 == '=') { ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_ASSIGN_ADD; } else { if (infix_count && YIELDS_AN_OPERAND(infix[infix_count - 1].symbol)) { if (cp1 == '+') { // For consistency, assume that since the previous item is an operand (even if it's // ')'), this is a post-op that applies to that operand. For example, the following // are all treated the same for consistency (implicit concatenation where the '.' // is omitted is rare anyway). // x++ y // x ++ y // x ++y // The following implicit concat is deliberately unsupported: // "string" ++x // The ++ above is seen as applying to the string because it doesn't seem worth // the complexity to distinguish between expressions that can accept a post-op // and those that can't (operands other than variables can have a post-op; // e.g. (x:=y)++). ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_POST_INCREMENT; } else this_infix_item.symbol = SYM_ADD; } else if (cp1 == '+') // Pre-increment. { ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_PRE_INCREMENT; } else // Remove unary pluses from consideration since they do not change the calculation. --infix_count; // Counteract the loop's increment. } break; case '-': if (cp1 == '=') { ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_ASSIGN_SUBTRACT; break; } // Otherwise (since above didn't "break"): // Must allow consecutive unary minuses because otherwise, the following example // would not work correctly when y contains a negative value: var := 3 * -y if (infix_count && YIELDS_AN_OPERAND(infix[infix_count - 1].symbol)) { if (cp1 == '-') { // See comments at SYM_POST_INCREMENT about this section. ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_POST_DECREMENT; } else this_infix_item.symbol = SYM_SUBTRACT; } else if (cp1 == '-') // Pre-decrement. { ++cp; // An additional increment to have loop skip over the operator's second symbol. this_infix_item.symbol = SYM_PRE_DECREMENT; } else // Unary minus. { // Set default for cases where the processing below this line doesn't determine // it's a negative numeric literal: this_infix_item.symbol = SYM_NEGATIVE; // v1.0.40.06: The smallest signed 64-bit number (-0x8000000000000000) wasn't properly // supported in previous versions because its unary minus was being seen as an operator, // and thus the raw number was being passed as a positive to _atoi64() or _strtoi64(), // neither of which would recognize it as a valid value. To correct this, a unary // minus followed by a raw numeric literal is now treated as a single literal number // rather than unary minus operator followed by a positive number. // // To be a valid "literal negative number", the character immediately following // the unary minus must not be: // 1) Whitespace (atoi() and such don't support it, nor is it at all conventional). // 2) An open-parenthesis such as the one in -(x). // 3) Another unary minus or operator such as --x (which is the pre-decrement operator). // To cover the above and possibly other unforeseen things, insist that the first // character be a digit (even a hex literal must start with 0). if ((cp1 >= '0' && cp1 <= '9') || cp1 == '.') // v1.0.46.01: Recognize dot too, to support numbers like -.5. { for (op_end = cp + 2; !_tcschr(EXPR_OPERAND_TERMINATORS_EX_DOT, *op_end); ++op_end); // Find the end of this number (can be '\0'). // 1.0.46.11: Due to obscurity, no changes have been made here to support scientific // notation followed by the power operator; e.g. -1.0e+1**5. if (!this_deref || op_end < this_deref->marker) // Detect numeric double derefs such as one created via "12%i% = value". { // Because the power operator takes precedence over unary minus, don't collapse // unary minus into a literal numeric literal if the number is immediately // followed by the power operator. This is correct behavior even for // -0x8000000000000000 because -0x8000000000000000**2 would in fact be undefined // because ** is higher precedence than unary minus and +0x8000000000000000 is // beyond the signed 64-bit range. SEE ALSO the comments higher above. // Use a temp variable because numeric_literal requires that op_end be set properly: LPTSTR pow_temp = omit_leading_whitespace(op_end); if (!(pow_temp[0] == '*' && pow_temp[1] == '*')) goto numeric_literal; // Goto is used for performance and also as a patch to minimize the chance of breaking other things via redesign. //else it's followed by pow. Since pow is higher precedence than unary minus, // leave this unary minus as an operator so that it will take effect after the pow. diff --git a/source/window.cpp b/source/window.cpp index bb1a0d9..2d1dfe0 100644 --- a/source/window.cpp +++ b/source/window.cpp @@ -1045,830 +1045,843 @@ int MsgBox(LPCTSTR aText, UINT uType, LPTSTR aTitle, double aTimeout, HWND aOwne // In the below, make the MsgBox owned by the topmost window rather than our main // window, in case there's another modal dialog already displayed. The forces the // user to deal with the modal dialogs starting with the most recent one, which // is what we want. Otherwise, if a middle dialog was dismissed, it probably // won't be able to return which button was pressed to its original caller. // UPDATE: It looks like these modal dialogs can't own other modal dialogs, // so disabling this: /* HWND topmost = GetTopWindow(g_hWnd); if (!topmost) // It has no child windows. topmost = g_hWnd; */ // Unhide the main window, but have it minimized. This creates a task // bar button so that it's easier the user to remember that a dialog // is open and waiting (there are probably better ways to handle // this whole thing). UPDATE: This isn't done because it seems // best not to have the main window be inaccessible until the // dialogs are dismissed (in case ever want to use it to display // status info, etc). It seems that MessageBoxes get their own // task bar button when they're not AppModal, which is one of the // main things I wanted, so that's good too): // if (!IsWindowVisible(g_hWnd) || !IsIconic(g_hWnd)) // ShowWindowAsync(g_hWnd, SW_SHOWMINIMIZED); /* If the script contains a line such as "#y::MsgBox, test", and a hotkey is used to activate Windows Explorer and another hotkey is then used to invoke a MsgBox, that MsgBox will be psuedo-minimized or invisible, even though it does have the input focus. This attempt to fix it didn't work, so something is probably checking the physical key state of LWIN/RWIN and seeing that they're down: modLR_type modLR_now = GetModifierLRState(); modLR_type win_keys_down = modLR_now & (MOD_LWIN | MOD_RWIN); if (win_keys_down) SetModifierLRStateSpecific(win_keys_down, modLR_now, KEYUP); */ // Note: Even though when multiple messageboxes exist, they might be // destroyed via a direct call to their WindowProc from our message pump's // DispatchMessage, or that of another MessageBox's message pump, it // appears that MessageBox() is designed to be called recursively like // this, since it always returns the proper result for the button on the // actual MessageBox it originally invoked. In other words, if a bunch // of Messageboxes are displayed, and this user dismisses an older // one prior to dealing with a newer one, all the MessageBox() // return values will still wind up being correct anyway, at least // on XP. The only downside to the way this is designed is that // the keyboard can't be used to navigate the buttons on older // messageboxes (only the most recent one). This is probably because // the message pump of MessageBox() isn't designed to properly dispatch // keyboard messages to other MessageBox window instances. I tried // to fix that by making our main message pump handle all messages // for all dialogs, but that turns out to be pretty complicated, so // I abandoned it for now. // Note: It appears that MessageBox windows, and perhaps all modal dialogs in general, // cannot own other windows. That's too bad because it would have allowed each new // MsgBox window to be owned by any previously existing one, so that the user would // be forced to close them in order if they were APPL_MODAL. But it's not too big // an issue since the only disadvantage is that the keyboard can't be use to // to navigate in MessageBoxes other than the most recent. And it's actually better // the way it is now in the sense that the user can dismiss the messageboxes out of // order, which might (in rare cases) be desirable. if (aTimeout > 2147483) // This is approximately the max number of seconds that SetTimer can handle. aTimeout = 2147483; if (aTimeout < 0) // But it can be equal to zero to indicate no timeout at all. aTimeout = 0.1; // A value that might cue the user that something is wrong. // For the above: // MsgBox's smart comma handling will usually prevent negatives due to the fact that it considers // a negative to be part of the text param. But if it does happen, timeout after a short time, // which may signal the user that the script passed a bad parameter. // v1.0.33: The following is a workaround for the fact that an MsgBox with only an OK button // doesn't obey EndDialog()'s parameter: g->DialogHWND = NULL; g->MsgBoxTimedOut = false; // At this point, we know a dialog will be displayed. See macro's comments for details: DIALOG_PREP // Must be done prior to POST_AHK_DIALOG() below. POST_AHK_DIALOG((DWORD)(aTimeout * 1000)) ++g_nMessageBoxes; // This value will also be used as the Timer ID if there's a timeout. g->MsgBoxResult = MessageBox(aOwner, text, title, uType); --g_nMessageBoxes; // Above's use of aOwner: MsgBox, FileSelectFile, and other dialogs seem to consider aOwner to be NULL // when aOwner is minimized or hidden. DIALOG_END // If there's a timer, kill it for performance reasons since it's no longer needed. // Actually, this isn't easy to do because we don't know what the HWND of the MsgBox // window was, so don't bother: //if (aTimeout != 0.0) // KillTimer(...); // if (!g_nMessageBoxes) // ShowWindowAsync(g_hWnd, SW_HIDE); // Hide the main window if it no longer has any child windows. // else // This is done so that the next message box of ours will be brought to the foreground, // to remind the user that they're still out there waiting, and for convenience. // Update: It seems bad to do this in cases where the user intentionally wants the older // messageboxes left in the background, to deal with them later. So, in those cases, // we might be doing more harm than good because the user's foreground window would // be intrusively changed by this: //WinActivateOurTopDialog(); // The following comment is apparently not always true -- sometimes the AHK_TIMEOUT from // EndDialog() is received correctly. But I haven't discovered the circumstances of how // and why the behavior varies: // Unfortunately, it appears that MessageBox() will return zero rather // than AHK_TIMEOUT that was specified in EndDialog() at least under WinXP. if (g->MsgBoxTimedOut || (!g->MsgBoxResult && aTimeout > 0)) // v1.0.33: Added g->MsgBoxTimedOut, see comment higher above. // Assume it timed out rather than failed, since failure should be VERY rare. g->MsgBoxResult = AHK_TIMEOUT; // else let the caller handle the display of the error message because only it knows // whether to also tell the user something like "the script will not continue". return g->MsgBoxResult; } HWND FindOurTopDialog() // Returns the HWND of our topmost MsgBox or FileOpen dialog (and perhaps other types of modal // dialogs if they are of class #32770) even if it wasn't successfully brought to // the foreground here. // Using Enum() seems to be the only easy way to do this, since these modal MessageBoxes are // *owned*, not children of the main window. There doesn't appear to be any easier way to // find out which windows another window owns. GetTopWindow(), GetActiveWindow(), and GetWindow() // do not work for this purpose. And using FindWindow() discouraged because it can hang // in certain circumstances (Enum is probably just as fast anyway). { // The return value of EnumWindows() is probably a raw indicator of success or failure, // not whether the Enum found something or continued all the way through all windows. // So don't bother using it. pid_and_hwnd_type pid_and_hwnd; pid_and_hwnd.pid = GetCurrentProcessId(); pid_and_hwnd.hwnd = NULL; // Init. Called function will set this for us if it finds a match. EnumWindows(EnumDialog, (LPARAM)&pid_and_hwnd); return pid_and_hwnd.hwnd; } BOOL CALLBACK EnumDialog(HWND aWnd, LPARAM lParam) // lParam should be a pointer to a ProcessId (ProcessIds are always non-zero?) // To continue enumeration, the function must return TRUE; to stop enumeration, it must return FALSE. { pid_and_hwnd_type &pah = *(pid_and_hwnd_type *)lParam; // For performance and convenience. if (!lParam || !pah.pid) return FALSE; DWORD pid; GetWindowThreadProcessId(aWnd, &pid); if (pid == pah.pid) { TCHAR buf[32]; GetClassName(aWnd, buf, _countof(buf)); // This is the class name for windows created via MessageBox(), GetOpenFileName(), and probably // other things that use modal dialogs: if (!_tcscmp(buf, _T("#32770"))) { pah.hwnd = aWnd; // An output value for the caller. return FALSE; // We're done. } } return TRUE; // Keep searching. } struct owning_struct {HWND owner_hwnd; HWND first_child;}; HWND WindowOwnsOthers(HWND aWnd) // Only finds owned windows if they are visible, by design. { owning_struct own = {aWnd, NULL}; EnumWindows(EnumParentFindOwned, (LPARAM)&own); return own.first_child; } BOOL CALLBACK EnumParentFindOwned(HWND aWnd, LPARAM lParam) { HWND owner_hwnd = GetWindow(aWnd, GW_OWNER); // Note: Many windows seem to own other invisible windows that have blank titles. // In our case, require that it be visible because we don't want to return an invisible // window to the caller because such windows aren't designed to be activated: if (owner_hwnd && owner_hwnd == ((owning_struct *)lParam)->owner_hwnd && IsWindowVisible(aWnd)) { ((owning_struct *)lParam)->first_child = aWnd; return FALSE; // Match found, we're done. } return TRUE; // Continue enumerating. } HWND GetNonChildParent(HWND aWnd) // Returns the first ancestor of aWnd that isn't itself a child. aWnd itself is returned if // it is not a child. Returns NULL only if aWnd is NULL. Also, it should always succeed // based on the axiom that any window with the WS_CHILD style (aka WS_CHILDWINDOW) must have // a non-child ancestor somewhere up the line. // This function doesn't do anything special with owned vs. unowned windows. Despite what MSDN // says, GetParent() does not return the owner window, at least in some cases on Windows XP // (e.g. BulletProof FTP Server). It returns NULL instead. In any case, it seems best not to // worry about owner windows for this function's caller (MouseGetPos()), since it might be // desirable for that command to return the owner window even though it can't actually be // activated. This is because attempts to activate an owner window should automatically cause // the OS to activate the topmost owned window instead. In addition, the owner window may // contain the actual title or text that the user is interested in. UPDATE: Due to the fact // that this function retrieves the first parent that's not a child window, it's likely that // that window isn't its owner anyway (since the owner problem usually applies to a parent // window being owned by some controlling window behind it). { if (!aWnd) return aWnd; HWND parent, parent_prev; for (parent_prev = aWnd; ; parent_prev = parent) { if (!(GetWindowLong(parent_prev, GWL_STYLE) & WS_CHILD)) // Found the first non-child parent, so return it. return parent_prev; // Because Windows 95 doesn't support GetAncestor(), we'll use GetParent() instead: if ( !(parent = GetParent(parent_prev)) ) return parent_prev; // This will return aWnd if aWnd has no parents. } } HWND GetTopChild(HWND aParent) { if (!aParent) return aParent; HWND hwnd_top, next_top; // Get the topmost window of the topmost window of... // i.e. Since child windows can also have children, we keep going until // we reach the "last topmost" window: for (hwnd_top = GetTopWindow(aParent) ; hwnd_top && (next_top = GetTopWindow(hwnd_top)) ; hwnd_top = next_top); //if (!hwnd_top) //{ // MsgBox("no top"); // return FAIL; //} //else //{ // //if (GetTopWindow(hwnd_top)) // // hwnd_top = GetTopWindow(hwnd_top); // char class_name[64]; // GetClassName(next_top, class_name, sizeof(class_name)); // MsgBox(class_name); //} return hwnd_top ? hwnd_top : aParent; // Caller relies on us never returning NULL if aParent is non-NULL. } bool IsWindowHung(HWND aWnd) { if (!aWnd) return false; // OLD, SLOWER METHOD: // Don't want to use a long delay because then our messages wouldn't get processed // in a timely fashion. But I'm not entirely sure if the 10ms delay used below // is even used by the function in this case? Also, the docs aren't clear on whether // the function returns success or failure if the window is hung (probably failure). // If failure, perhaps you have to call GetLastError() to determine whether it failed // due to being hung or some other reason? Does the output param dwResult have any // useful info in this case? I expect what will happen is that in most cases, the OS // will already know that the window is hung. However, if the window just became hung // in the last 5 seconds, I think it may take the remainder of the 5 seconds for the OS // to notice it. However, allowing it the option of sleeping up to 5 seconds seems // really bad, since keyboard and mouse input would probably be frozen (actually it // would just be really laggy because the OS would bypass the hook during that time). // So some compromise value seems in order. 500ms seems about right. UPDATE: Some // windows might need longer than 500ms because their threads are engaged in // heavy operations. Since this method is only used as a fallback method now, // it seems best to give them the full 5000ms default, which is what (all?) Windows // OSes use as a cutoff to determine whether a window is "not responding": DWORD_PTR dwResult; #define Slow_IsWindowHung !SendMessageTimeout(aWnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 5000, &dwResult) // NEW, FASTER METHOD: // This newer method's worst-case performance is at least 30x faster than the worst-case // performance of the old method that uses SendMessageTimeout(). // And an even worse case can be envisioned which makes the use of this method // even more compelling: If the OS considers a window NOT to be hung, but the // window's message pump is sluggish about responding to the SendMessageTimeout() (perhaps // taking 2000ms or more to respond due to heavy disk I/O or other activity), the old method // will take several seconds to return, causing mouse and keyboard lag if our hook(s) // are installed; not to mention making our app's windows, tray menu, and other GUI controls // unresponsive during that time). But I believe in this case the new method will return // instantly, since the OS has been keeping track in the background, and can tell us // immediately that the window isn't hung. // Here are some seemingly contradictory statements uttered by MSDN. Perhaps they're // not contradictory if the first sentence really means "by a different thread of the same // process": // "If the specified window was created by a different thread, the system switches to that // thread and calls the appropriate window procedure. Messages sent between threads are // processed only when the receiving thread executes message retrieval code. The sending // thread is blocked until the receiving thread processes the message." #ifdef CONFIG_WIN9X if (g_os.IsWin9x()) { typedef BOOL (WINAPI *MyIsHungThread)(DWORD); static MyIsHungThread IsHungThread = (MyIsHungThread)GetProcAddress(GetModuleHandle(_T("user32")) , "IsHungThread"); // When function not available, fall back to the old method: return IsHungThread ? IsHungThread(GetWindowThreadProcessId(aWnd, NULL)) : Slow_IsWindowHung; } #endif // Otherwise: NT/2k/XP/2003 or later, so try to use the newer method. // The use of IsHungAppWindow() (supported under Win2k+) is discouraged by MS, // but it's useful to prevent the script from getting hung when it tries to do something // to a hung window. typedef BOOL (WINAPI *MyIsHungAppWindow)(HWND); static MyIsHungAppWindow IsHungAppWindow = (MyIsHungAppWindow)GetProcAddress(GetModuleHandle(_T("user32")) , "IsHungAppWindow"); return IsHungAppWindow ? IsHungAppWindow(aWnd) : Slow_IsWindowHung; } int GetWindowTextTimeout(HWND aWnd, LPTSTR aBuf, INT_PTR aBufSize, UINT aTimeout) // This function must be kept thread-safe because it may be called (indirectly) by hook thread too. // aBufSize is an int so that any negative values passed in from caller are not lost. // Returns the length of what would be copied (not including the zero terminator). // In addition, if aBuf is not NULL, the window text is copied into aBuf (not to exceed aBufSize). // AutoIt3 author indicates that using WM_GETTEXT vs. GetWindowText() sometimes yields more text. // Perhaps this is because GetWindowText() has built-in protection against hung windows and // thus isn't actually sending WM_GETTEXT. The method here is hopefully the best of both worlds // (protection against hung windows causing our thread to hang, and getting more text). // Another tidbit from MSDN about SendMessage() that might be of use here sometime: // "However, the sending thread will process incoming nonqueued (those sent directly to a window // procedure) messages while waiting for its message to be processed. To prevent this, use // SendMessageTimeout with SMTO_BLOCK set." Currently not using SMTO_BLOCK because it // doesn't seem necessary. // Update: GetWindowText() is so much faster than SendMessage() and SendMessageTimeout(), at // least on XP, so GetWindowTextTimeout() should probably only be used when getting the max amount // of text is important (e.g. this function can fetch the text in a RichEdit20A control and // other edit controls, whereas GetWindowText() doesn't). This function is used to implement // things like WinGetText and ControlGetText, in which getting the maximum amount and types // of text is more important than performance. { if (!aWnd || (aBuf && aBufSize < 1)) // No HWND or no room left in buffer (some callers rely on this check). return 0; // v1.0.40.04: Fixed to return 0 rather than setting aBuf to NULL and continuing (callers don't want that). // Override for Win95 because AutoIt3 author says it might crash otherwise: if (aBufSize > WINDOW_TEXT_SIZE && g_os.IsWin95()) aBufSize = WINDOW_TEXT_SIZE; LRESULT result, length; if (aBuf) { *aBuf = '\0'; // Init just to get it out of the way in case of early return/error. if (aBufSize == 1) // Room only for the terminator, so go no further (some callers rely on this check). return 0; // Below demonstrated that GetWindowText() is dramatically faster than either SendMessage() // or SendMessageTimeout() (noticeably faster when you have hotkeys that activate // windows, or toggle between two windows): //return GetWindowText(aWnd, aBuf, aBufSize); //return (int)SendMessage(aWnd, WM_GETTEXT, (WPARAM)aBufSize, (LPARAM)aBuf); // Don't bother calling IsWindowHung() because the below call will return // nearly instantly if the OS already "knows" that the target window has // be unresponsive for 5 seconds or so (i.e. it keeps track of such things // on an ongoing basis, at least XP seems to). result = SendMessageTimeout(aWnd, WM_GETTEXT, (WPARAM)aBufSize, (LPARAM)aBuf , SMTO_ABORTIFHUNG, aTimeout, (PDWORD_PTR) &length); if (length >= aBufSize) // Happens sometimes (at least ==aBufSize) for apps that wrongly include the terminator in the reported length. length = aBufSize - 1; // Override. // v1.0.40.04: The following check was added because when the text is too large to to fit in the // buffer, the OS (or at least certain applications such as AIM) return a length that *includes* // the zero terminator, violating the documented behavior of WM_GETTEXT. In case the returned // length is too long by 1 (or even more than 1), calculate the length explicitly by checking if // there's another terminator to the left of the indicated length. The following loop // is used in lieu of strlen() for performance reasons (because sometimes the text is huge). // It assumes that there will be no more than one additional terminator to the left of the // indicated length, which so far seems to be true: for (LPTSTR cp = aBuf + length; cp >= aBuf; --cp) { if (!*cp) { // Keep going to the left until the last consecutive terminator is found. // Necessary for AIM when compiled in release mode (but not in debug mode // for some reason!): for (; cp > aBuf && !cp[-1]; --cp); // Self-contained loop. Verified correct. length = cp - aBuf; break; } } // If the above loop didn't "break", a terminator wasn't found. // Terminate explicitly because MSDN docs aren't clear that it will always be terminated automatically. // Update: This also protects against misbehaving apps that might handle the WM_GETTEXT message // rather than passing it to DefWindowProc() but that don't terminate the buffer. This has been // confirmed to be necessary at least for AIM when aBufSize==1 (although 1 is no longer possible due // to a check that has been added further above): aBuf[length] = '\0'; } else { result = SendMessageTimeout(aWnd, WM_GETTEXTLENGTH, 0, 0, SMTO_ABORTIFHUNG, aTimeout, (PDWORD_PTR)&length); // The following can be temporarily uncommented out to demonstrate how some apps such as AIM's // write-an-instant-message window have some controls that respond to WM_GETTEXTLENGTH with a // length that's completely different than the length with which they respond to WM_GETTEXT. // Here are some of the discrepancies: // WM_GETTEXTLENGTH vs. WM_GETTEXT: // 92 vs. 318 (bigger) // 50 vs. 159 (bigger) // 3 vs. 0 (smaller) // 24 vs. 88 (etc.) // 80 vs. 188 // 24 vs. 88 // 80 vs. 188 //char buf[32000]; //LRESULT length2; //result = SendMessageTimeout(aWnd, WM_GETTEXT, (WPARAM)sizeof(buf), (LPARAM)buf // , SMTO_ABORTIFHUNG, aTimeout, (LPDWORD)&length2); //if (length2 != length) //{ // int x = 0; // Put breakpoint here. //} // An attempt to fix the size estimate to be larger for misbehaving apps like AIM, but it's ineffective // so commented out: //if (!length) // length = GetWindowTextLength(aWnd); } // "length" contains the length of what was (or would have been) copied, not including the terminator: return result ? (int)length : 0; // "result" is zero upon failure or timeout. } /////////////////////////////////////////////////////////////////////////// ResultType WindowSearch::SetCriteria(global_struct &aSettings, LPTSTR aTitle, LPTSTR aText, LPTSTR aExcludeTitle, LPTSTR aExcludeText) // Returns FAIL if the new criteria can't possibly match a window (due to ahk_id being in invalid // window or the specified ahk_group not existing). Otherwise, it returns OK. // Callers must ensure that aText, aExcludeTitle, and aExcludeText point to buffers whose contents // will be available for the entire duration of the search. In other words, the caller should not // call MsgSleep() in a way that would allow another thread to launch and overwrite the contents // of the sDeref buffer (which might contain the contents). Things like mFoundHWND and mFoundCount // are not initialized here because sometimes the caller changes the criteria without wanting to // reset the search. // This function must be kept thread-safe because it may be called (indirectly) by hook thread too. { // Set any criteria which are not context sensitive. It doesn't seem necessary to make copies of // mCriterionText, mCriterionExcludeTitle, and mCriterionExcludeText because they're never altered // here, nor does there seem to be a risk that deref buffer's contents will get overwritten // while this set of criteria is in effect because our callers never allow interrupting script-threads // *during* the duration of any one set of criteria. bool exclude_title_became_non_blank = *aExcludeTitle && !*mCriterionExcludeTitle; mCriterionExcludeTitle = aExcludeTitle; mCriterionExcludeTitleLength = _tcslen(mCriterionExcludeTitle); // Pre-calculated for performance. mCriterionText = aText; mCriterionExcludeText = aExcludeText; mSettings = &aSettings; DWORD orig_criteria = mCriteria; TCHAR *ahk_flag, *cp, buf[MAX_VAR_NAME_LENGTH + 1]; int criteria_count; size_t size; for (mCriteria = 0, ahk_flag = aTitle, criteria_count = 0;; ++criteria_count, ahk_flag += 4) // +4 only since an "ahk_" string that isn't qualified may have been found. { if ( !(ahk_flag = tcscasestr(ahk_flag, _T("ahk_"))) ) // No other special strings are present. { if (!criteria_count) // Since no special "ahk_" criteria were present, it is CRITERION_TITLE by default. { mCriteria = CRITERION_TITLE; // In this case, there is only one criterion. tcslcpy(mCriterionTitle, aTitle, _countof(mCriterionTitle)); mCriterionTitleLength = _tcslen(mCriterionTitle); // Pre-calculated for performance. } break; } // Since above didn't break, another instance of "ahk_" has been found. To reduce ambiguity, // the following requires that any "ahk_" criteria beyond the first be preceded by at least // one space or tab: if (criteria_count && !IS_SPACE_OR_TAB(ahk_flag[-1])) // Relies on short-circuit boolean order. { --criteria_count; // Decrement criteria_count to compensate for the loop's increment. continue; } // Since above didn't "continue", it meets the basic test. But is it an exact match for one of the // special criteria strings? If not, it's really part of the title criterion instead. cp = ahk_flag + 4; if (!_tcsnicmp(cp, _T("id"), 2)) { cp += 2; mCriteria |= CRITERION_ID; mCriterionHwnd = (HWND)ATOU64(cp); // Note that this can validly be the HWND of a child window; i.e. ahk_id %ChildWindowHwnd% is supported. if (mCriterionHwnd != HWND_BROADCAST && !IsWindow(mCriterionHwnd)) // Checked here once rather than each call to IsMatch(). { mCriterionHwnd = NULL; return FAIL; // Inform caller of invalid criteria. No need to do anything else further below. } } else if (!_tcsnicmp(cp, _T("pid"), 3)) { cp += 3; mCriteria |= CRITERION_PID; mCriterionPID = ATOU(cp); } - else if (!_tcsnicmp(cp, _T("exe"), 3)) + else if (!_tcsnicmp(cp, _T("group"), 5)) { - cp += 3; - mCriteria |= CRITERION_PATH; - tcslcpy(mCriterionPath, omit_leading_whitespace(cp), _countof(mCriterionPath)); - // Allow something like "ahk_exe firefox.exe" to be an exact match for the process name - // instead of full path, but for flexibility, always use full path when in regex mode. - mCriterionPathIsNameOnly = mSettings->TitleMatchMode != FIND_REGEX && !_tcschr(mCriterionPath, '\\'); + cp += 5; + mCriteria |= CRITERION_GROUP; + tcslcpy(buf, omit_leading_whitespace(cp), _countof(buf)); + if (cp = StrChrAny(buf, _T(" \t"))) // Group names can't contain spaces, so terminate at the first one to exclude any "ahk_" criteria that come afterward. + *cp = '\0'; + if ( !(mCriterionGroup = g_script.FindGroup(buf)) ) + return FAIL; // No such group: Inform caller of invalid criteria. No need to do anything else further below. } - else if (!_tcsnicmp(cp, _T("class"), 5)) + else { - cp += 5; - mCriteria |= CRITERION_CLASS; + // Fix for v1.1.09: ahk_exe is handled with ahk_class so that it can be followed by + // another criterion, such as in "ahk_exe explorer.exe ahk_class CabinetWClass". + TCHAR *criterion = NULL; + if (!_tcsnicmp(cp, _T("exe"), 3)) + { + cp += 3; + mCriteria |= CRITERION_PATH; + criterion = mCriterionPath; + + } + else if (!_tcsnicmp(cp, _T("class"), 5)) + { + cp += 5; + mCriteria |= CRITERION_CLASS; + criterion = mCriterionClass; + } + else // It doesn't qualify as a special criteria name even though it starts with "ahk_". + { + --criteria_count; // Decrement criteria_count to compensate for the loop's increment. + continue; + } + // In the following line, it may have been preferable to skip only zero or one spaces rather than // calling omit_leading_whitespace(). But now this should probably be kept for backward compatibility. // Besides, even if it's possible for a class name to start with a space, a RegEx dot or other symbol // can be used to match it via SetTitleMatchMode RegEx. - tcslcpy(mCriterionClass, omit_leading_whitespace(cp), _countof(mCriterionClass)); // Copy all of the remaining string to simplify the below. - for (cp = mCriterionClass; cp = tcscasestr(cp, _T("ahk_")); cp += 4) // Fix for v1.0.47.06: strstr() changed to strcasestr() for consistency with the other sections. + tcslcpy(criterion, omit_leading_whitespace(cp), SEARCH_PHRASE_SIZE); // Copy all of the remaining string to simplify the below. + for (cp = criterion; cp = tcscasestr(cp, _T("ahk_")); cp += 4) // Fix for v1.0.47.06: strstr() changed to strcasestr() for consistency with the other sections. { // This loop truncates any other criteria from the class criteria. It's not a complete // solution because it doesn't validate that what comes after the "ahk_" string is a // valid criterion name. But for it not to be and yet also be part of some valid class // name seems far too unlikely to worry about. It would have to be a legitimate class name // such as "ahk_class SomeClassName ahk_wrong". - if (cp == mCriterionClass) // This check prevents underflow in the next check. + if (cp == criterion) // This check prevents underflow in the next check. { *cp = '\0'; break; } else if (IS_SPACE_OR_TAB(cp[-1])) { cp[-1] = '\0'; break; } //else assume this "ahk_" string is part of the literal text, continue looping in case // there is a legitimate "ahk_" string after this one. } // for() - } - else if (!_tcsnicmp(cp, _T("group"), 5)) - { - cp += 5; - mCriteria |= CRITERION_GROUP; - tcslcpy(buf, omit_leading_whitespace(cp), _countof(buf)); - if (cp = StrChrAny(buf, _T(" \t"))) // Group names can't contain spaces, so terminate at the first one to exclude any "ahk_" criteria that come afterward. - *cp = '\0'; - if ( !(mCriterionGroup = g_script.FindGroup(buf)) ) - return FAIL; // No such group: Inform caller of invalid criteria. No need to do anything else further below. - } - else // It doesn't qualify as a special criteria name even though it starts with "ahk_". - { - --criteria_count; // Decrement criteria_count to compensate for the loop's increment. - continue; + + if (criterion == mCriterionPath) + { + // Allow something like "ahk_exe firefox.exe" to be an exact match for the process name + // instead of full path, but for flexibility, always use full path when in regex mode. + mCriterionPathIsNameOnly = mSettings->TitleMatchMode != FIND_REGEX && !_tcschr(mCriterionPath, '\\'); + } } // Since above didn't return or continue, a valid "ahk_" criterion has been discovered. // If this is the first such criterion, any text that lies to its left should be interpreted // as CRITERION_TITLE. However, for backward compatibility it seems best to disqualify any title // consisting entirely of whitespace. This is because some scripts might have a variable containing // whitespace followed by the string ahk_class, etc. (however, any such whitespace is included as a // literal part of the title criterion for flexibility and backward compatibility). if (!criteria_count && ahk_flag > omit_leading_whitespace(aTitle)) { mCriteria |= CRITERION_TITLE; // Omit exactly one space or tab from the title criterion. That space or tab is the one // required to delimit the special "ahk_" string. Any other spaces or tabs to the left of // that one are considered literal (for flexibility): size = ahk_flag - aTitle; // This will always be greater than one due to other checks above, which will result in at least one non-whitespace character in the title criterion. if (size > _countof(mCriterionTitle)) // Prevent overflow. size = _countof(mCriterionTitle); tcslcpy(mCriterionTitle, aTitle, size); // Copy only the eligible substring as the criteria. mCriterionTitleLength = _tcslen(mCriterionTitle); // Pre-calculated for performance. } } // Since this function doesn't change mCandidateParent, there is no need to update the candidate's // attributes unless the type of criterion has changed or if mExcludeTitle became non-blank as // a result of our action above: if (mCriteria != orig_criteria || exclude_title_became_non_blank) UpdateCandidateAttributes(); // In case mCandidateParent isn't NULL, fetch different attributes based on what was set above. //else for performance reasons, avoid unnecessary updates. return OK; } void WindowSearch::UpdateCandidateAttributes() // This function must be kept thread-safe because it may be called (indirectly) by hook thread too. { // Nothing to do until SetCandidate() is called with a non-NULL candidate and SetCriteria() // has been called for the first time (otherwise, mCriterionExcludeTitle and other things // are not yet initialized: if (!mCandidateParent || !mCriteria) return; if ((mCriteria & CRITERION_TITLE) || *mCriterionExcludeTitle) // Need the window's title in both these cases. if (!GetWindowText(mCandidateParent, mCandidateTitle, _countof(mCandidateTitle))) *mCandidateTitle = '\0'; // Failure or blank title is okay. if (mCriteria & CRITERION_PID) // In which case mCriterionPID should already be filled in, though it might be an explicitly specified zero. GetWindowThreadProcessId(mCandidateParent, &mCandidatePID); if (mCriteria & CRITERION_PATH) { DWORD dwPid; if (GetWindowThreadProcessId(mCandidateParent, &dwPid)) if (!GetProcessName(dwPid, mCandidatePath, _countof(mCandidatePath), mCriterionPathIsNameOnly)) *mCandidatePath = '\0'; } if (mCriteria & CRITERION_CLASS) GetClassName(mCandidateParent, mCandidateClass, _countof(mCandidateClass)); // Limit to WINDOW_CLASS_SIZE in this case since that's the maximum that can be searched. // Nothing to do for these: //CRITERION_GROUP: Can't be pre-processed at this stage. //CRITERION_ID: It is mCandidateParent, which has already been set by SetCandidate(). } HWND WindowSearch::IsMatch(bool aInvert) // Caller must have called SetCriteria prior to calling this method, at least for the purpose of setting // mSettings to a valid address (and possibly other reasons). // This method returns the HWND of mCandidateParent if it matches the previously specified criteria // (title/pid/id/class/group) or NULL otherwise. Upon NULL, it doesn't reset mFoundParent or mFoundCount // in case previous match(es) were found when mFindLastMatch is in effect. // Thread-safety: With the following exception, this function must be kept thread-safe because it may be // called (indirectly) by hook thread too: The hook thread must never call here directly or indirectly with // mArrayStart!=NULL because the corresponding section below is probably not thread-safe. { if (!mCandidateParent || !mCriteria) // Nothing to check, so no match. return NULL; if ((mCriteria & CRITERION_TITLE) && *mCriterionTitle) // For performance, avoid the calls below (especially RegEx) when mCriterionTitle is blank (assuming it's even possible for it to be blank under these conditions). { switch(mSettings->TitleMatchMode) { case FIND_ANYWHERE: if (!_tcsstr(mCandidateTitle, mCriterionTitle)) // Suitable even if mCriterionTitle is blank, though that's already ruled out above. return NULL; break; case FIND_IN_LEADING_PART: if (_tcsncmp(mCandidateTitle, mCriterionTitle, mCriterionTitleLength)) // Suitable even if mCriterionTitle is blank, though that's already ruled out above. If it were possible, mCriterionTitleLength would be 0 and thus strncmp would yield 0 to indicate "strings are equal". return NULL; break; case FIND_REGEX: if (!RegExMatch(mCandidateTitle, mCriterionTitle)) return NULL; break; default: // Exact match. if (_tcscmp(mCandidateTitle, mCriterionTitle)) return NULL; } // If above didn't return, it's a match so far so continue onward to the other checks. } if (mCriteria & CRITERION_CLASS) // mCriterionClass is probably always non-blank when CRITERION_CLASS is present (harmless even if it isn't), so *mCriterionClass isn't checked. { if (mSettings->TitleMatchMode == FIND_REGEX) { if (!RegExMatch(mCandidateClass, mCriterionClass)) return NULL; } else // For backward compatibility, all other modes use exact-match for Class. if (_tcscmp(mCandidateClass, mCriterionClass)) // Doesn't match the required class name. return NULL; // If nothing above returned, it's a match so far so continue onward to the other checks. } // For the following, mCriterionPID would already be filled in, though it might be an explicitly specified zero. if ((mCriteria & CRITERION_PID) && mCandidatePID != mCriterionPID) // Doesn't match required PID. return NULL; //else it's a match so far, but continue onward in case there are other criteria. if (mCriteria & CRITERION_PATH) { if (mSettings->TitleMatchMode == FIND_REGEX) { if (!RegExMatch(mCandidatePath, mCriterionPath)) return NULL; } else if (_tcsicmp(mCandidatePath, mCriterionPath)) // Doesn't match the required path. return NULL; // If nothing above returned, it's a match so far so continue onward to the other checks. } // The following also handles the fact that mCriterionGroup might be NULL if the specified group // does not exist or was never successfully created: if ((mCriteria & CRITERION_GROUP) && (!mCriterionGroup || !mCriterionGroup->IsMember(mCandidateParent, *mSettings))) return NULL; // Isn't a member of specified group. //else it's a match so far, but continue onward in case there are other criteria (a little strange in this case, but might be useful). // CRITERION_ID is listed last since in terms of actual calling frequency, this part is hardly ever // executed: It's only ever called this way from WinActive(), and possibly indirectly by an ahk_group // that contains an ahk_id specification. It's also called by WinGetList()'s EnumWindows(), though // extremely rarely. It's also called this way from other places to determine whether an ahk_id window // matches the other criteria such as WinText, ExcludeTitle, and mAlreadyVisited. // mCriterionHwnd should already be filled in, though it might be an explicitly specified zero. // Note: IsWindow(mCriterionHwnd) was already called by SetCriteria(). if ((mCriteria & CRITERION_ID) && mCandidateParent != mCriterionHwnd) // Doesn't match the required HWND. return NULL; //else it's a match so far, but continue onward in case there are other criteria. // The above would have returned if the candidate window isn't a match for what was specified by // the script's WinTitle parameter. So now check that the ExcludeTitle criterion is satisfied. // This is done prior to checking WinText/ExcludeText for performance reasons: if (*mCriterionExcludeTitle) { switch(mSettings->TitleMatchMode) { case FIND_ANYWHERE: if (_tcsstr(mCandidateTitle, mCriterionExcludeTitle)) return NULL; break; case FIND_IN_LEADING_PART: if (!_tcsncmp(mCandidateTitle, mCriterionExcludeTitle, mCriterionExcludeTitleLength)) return NULL; break; case FIND_REGEX: if (RegExMatch(mCandidateTitle, mCriterionExcludeTitle)) return NULL; break; default: // Exact match. if (!_tcscmp(mCandidateTitle, mCriterionExcludeTitle)) return NULL; } // If above didn't return, WinTitle and ExcludeTitle are both satisfied. So continue // on below in case there is some WinText or ExcludeText to search. } if (!aInvert) // If caller specified aInvert==true, it will do the below instead of us. for (int i = 0; i < mAlreadyVisitedCount; ++i) if (mCandidateParent == mAlreadyVisited[i]) return NULL; if (*mCriterionText || *mCriterionExcludeText) // It's not quite a match yet since there are more criteria. { // Check the child windows for the specified criteria. // EnumChildWindows() will return FALSE (failure) in at least two common conditions: // 1) It's EnumChildProc callback returned false (i.e. it ended the enumeration prematurely). // 2) The specified parent has no children. // Since in both these cases GetLastError() returns ERROR_SUCCESS, we discard the return // value and just check mFoundChild to determine whether a match has been found: mFoundChild = NULL; // Init prior to each call, in case mFindLastMatch is true. EnumChildWindows(mCandidateParent, EnumChildFind, (LPARAM)this); if (!mFoundChild) // This parent has no matching child, or no children at all. return NULL; } // Since the above didn't return or none of the checks above were needed, it's a complete match. // If mFindLastMatch is true, this new value for mFoundParent will stay in effect until // overridden by another matching window later: if (!aInvert) { mFoundParent = mCandidateParent; ++mFoundCount; // This must be done prior to the mArrayStart section below. } //else aInvert==true, which means caller doesn't want the above set. if (mArrayStart) // Probably not thread-safe due to FindOrAddVar(), so hook thread must call only with NULL mArrayStart. { // Make it longer than Max var name so that FindOrAddVar() will be able to spot and report // var names that are too long: TCHAR var_name[MAX_VAR_NAME_LENGTH + 20]; Var *array_item = g_script.FindOrAddVar(var_name , sntprintf(var_name, _countof(var_name), _T("%s%u"), mArrayStart->mName, mFoundCount) , mArrayStart->IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL); if (array_item) array_item->AssignHWND(mFoundParent); //else no error reporting currently, since should be very rare. } // Fix for v1.0.30.01: Don't return mFoundParent because its NULL when aInvert is true. // At this stage, the candidate is a known match, so return it: return mCandidateParent; } /////////////////////////////////////////////////////////////////// void SetForegroundLockTimeout() { // Even though they may not help in all OSs and situations, this lends peace-of-mind. // (it doesn't appear to help on my XP?) if (g_os.IsWin98orLater() || g_os.IsWin2000orLater()) { // Don't check for failure since this operation isn't critical, and don't want // users continually haunted by startup error if for some reason this doesn't // work on their system: if (SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &g_OriginalTimeout, 0)) if (g_OriginalTimeout) // Anti-focus stealing measure is in effect. { // Set it to zero instead, disabling the measure: SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)0, SPIF_SENDCHANGE); // if (!SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)0, SPIF_SENDCHANGE)) // MsgBox("Enable focus-stealing: set-call to SystemParametersInfo() failed."); } // else // MsgBox("Enable focus-stealing: it was already enabled."); // else // MsgBox("Enable focus-stealing: get-call to SystemParametersInfo() failed."); } // else // MsgBox("Enable focus-stealing: neither needed nor supported under Win95 and WinNT."); } bool DialogPrep() // Having it as a function vs. macro should reduce code size due to expansion of macros inside. { bool thread_was_critical = g->ThreadIsCritical; g->ThreadIsCritical = false; g->AllowThreadToBeInterrupted = true; if (HIWORD(GetQueueStatus(QS_ALLEVENTS))) // See DIALOG_PREP for explanation. MsgSleep(-1); return thread_was_critical; // Caller is responsible for using this to later restore g->ThreadIsCritical. }
tinku99/ahkdll
7762d69a32558d4f8568ba9635508ad941e424b0
Fixed CriticalObject(objptr)
diff --git a/source/script2.cpp b/source/script2.cpp index e284d1a..ce23a79 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -13707,1025 +13707,1027 @@ BIF_DECL(BIF_DllCall) case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; if (IS_NUMERIC(token.symbol) || token.symbol == SYM_OBJECT) // The return type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } LPTSTR return_type_string[2]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. } else { return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { // Check validity of this arg's type and contents: if (IS_NUMERIC(aParam[i]->symbol)) // The arg type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // Otherwise, this arg's type-name is a string as it should be, so retrieve it: if (aParam[i]->symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). } else { arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (!function) // The function's address hasn't yet been determined. { function = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, &hmodule_to_free); if (!function) goto end; } //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, dyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, dyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = 1; 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. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = dyna_param[arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } end: if (hmodule_to_free) FreeLibrary(hmodule_to_free); } #endif BIF_DECL(BIF_CriticalObject) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; - CriticalObject *criticalobj = (CriticalObject*)TokenToObject(*aParam[0]); + CriticalObject *criticalobj; + if (!(criticalobj = (CriticalObject *)TokenToObject(*aParam[0]))) + criticalobj = (CriticalObject *)TokenToInt64(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } CriticalObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else obj->AddRef(); } // create new critical object and save reference CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Check if we own the critical section and release it if (TryEnterCriticalSection(this->lpCriticalSection)) { LeaveCriticalSection(this->lpCriticalSection); } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed while (!TryEnterCriticalSection(this->lpCriticalSection)) MsgSleep(-1); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } BIF_DECL(BIF_Lock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); EnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_TryLock) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TryEnterCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_UnLock) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); LeaveCriticalSection((LPCRITICAL_SECTION) TokenToInt64(*aParam[0])); } BIF_DECL(BIF_StrLen) // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. // Result is always an integer (caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need // to set it here). { // Loadtime validation has ensured that there's exactly one actual parameter. // Calling Length() is always valid for SYM_VAR because SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). aResultToken.value_int64 = (aParam[0]->symbol == SYM_VAR) ? (aParam[0]->var->MaybeWarnUninitialized(), aParam[0]->var->Length()) : _tcslen(TokenToString(*aParam[0], aResultToken.buf)); // Allow StrLen(numeric_expr) for flexibility. } BIF_DECL(BIF_SubStr) // Added in v1.0.46. { // Set default return value in case of early return. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. TCHAR haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR haystack = TokenToString(*aParam[0], haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). INT_PTR haystack_length = (INT_PTR)EXPR_TOKEN_LENGTH(aParam[0], haystack); // Load-time validation has ensured that at least the first two parameters are present: INT_PTR starting_offset = (INT_PTR)TokenToInt64(*aParam[1]) - 1; // The one-based starting position in haystack (if any). Convert it to zero-based. if (starting_offset > haystack_length) return; // Yield the empty string (a default set higher above). if (starting_offset < 0) // Same convention as RegExMatch/Replace(): Treat a StartingPos of 0 (offset -1) as "start at the string's last char". Similarly, treat negatives as starting further to the left of the end of the string. { starting_offset += haystack_length; if (starting_offset < 0) starting_offset = 0; } INT_PTR remaining_length_available = haystack_length - starting_offset; INT_PTR extract_length; if (aParamCount < 3) // No length specified, so extract all the remaining length. extract_length = remaining_length_available; else { if ( !(extract_length = (INT_PTR)TokenToInt64(*aParam[2])) ) // It has asked to extract zero characters. return; // Yield the empty string (a default set higher above). if (extract_length < 0) { extract_length += remaining_length_available; // Result is the number of characters to be extracted (i.e. after omitting the number of chars specified in extract_length). if (extract_length < 1) // It has asked to omit all characters. return; // Yield the empty string (a default set higher above). } else // extract_length > 0 if (extract_length > remaining_length_available) extract_length = remaining_length_available; } // Above has set extract_length to the exact number of characters that will actually be extracted. LPTSTR result = haystack + starting_offset; // This is the result except for the possible need to truncate it below. if (extract_length == remaining_length_available) // All of haystack is desired (starting at starting_offset). { aResultToken.marker = result; // No need for any copying or termination, just send back part of haystack. return; // Caller and Var:Assign() know that overlap is possible, so this seems safe. } // Otherwise, at least one character is being omitted from the end of haystack. if (!TokenSetResult(aResultToken, result, extract_length)) { // Yield the empty string (a default set higher above). } } BIF_DECL(BIF_InStr) { // Load-time validation has already ensured that at least two actual parameters are present. TCHAR needle_buf[MAX_NUMBER_SIZE]; LPTSTR haystack = TokenToString(*aParam[0], aResultToken.buf); LPTSTR needle = TokenToString(*aParam[1], needle_buf); // Result type will always be an integer: // Caller has set aResultToken.symbol to a default of SYM_INTEGER, so no need to set it here. // v1.0.43.03: Rather than adding a third value to the CaseSensitive parameter, it seems better to // obey StringCaseSense because: // 1) It matches the behavior of the equal operator (=) in expressions. // 2) It's more friendly for typical international uses because it avoids having to specify that special/third value // for every call of InStr. It's nice to be able to omit the CaseSensitive parameter every time and know that // the behavior of both InStr and its counterpart the equals operator are always consistent with each other. // 3) Avoids breaking existing scripts that may pass something other than true/false for the CaseSense parameter. StringCaseSenseType string_case_sense = (StringCaseSenseType)(aParamCount >= 3 && TokenToInt64(*aParam[2])); // Above has assigned SCS_INSENSITIVE (0) or SCS_SENSITIVE (1). If it's insensitive, resolve it to // be Locale-mode if the StringCaseSense mode is either case-sensitive or Locale-insensitive. if (g->StringCaseSense != SCS_INSENSITIVE && string_case_sense == SCS_INSENSITIVE) // Ordered for short-circuit performance. string_case_sense = SCS_INSENSITIVE_LOCALE; LPTSTR found_pos; INT_PTR offset = 0; // Set default. int occurrence_number = 1; // Set default. if (aParamCount >= 4) // There is a starting position present. { offset = (INT_PTR)TokenToInt64(*aParam[3]); // i.e. the fourth arg. if (aParamCount >= 5) occurrence_number = (int)TokenToInt64(*aParam[4]); // For offset validation and reverse search we need to know the length of haystack: INT_PTR haystack_length = EXPR_TOKEN_LENGTH(aParam[0], haystack); if (offset <= 0) // Special mode to search from the right side. { haystack_length += offset; // i.e. reduce haystack_length by the absolute value of offset. found_pos = (haystack_length >= 0) ? tcsrstr(haystack, haystack_length, needle, string_case_sense, occurrence_number) : NULL; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; // +1 to convert to 1-based, since 0 indicates "not found". return; } --offset; // Convert from one-based to zero-based. if (offset > haystack_length || occurrence_number < 1) { aResultToken.value_int64 = 0; // Match never found when offset is beyond length of string. return; } } // Since above didn't return: size_t needle_length = (occurrence_number > 1) ? EXPR_TOKEN_LENGTH(aParam[1], needle) : 1; // Avoid unnecessary _tcslen() if occurrence_number == 1, which is the most common case. int i; for (i = 1, found_pos = haystack + offset; ; ++i, found_pos += needle_length) if (!(found_pos = tcsstr2(found_pos, needle, string_case_sense)) || i == occurrence_number) break; aResultToken.value_int64 = found_pos ? (found_pos - haystack + 1) : 0; } void RegExSetSubpatternVars(LPCTSTR haystack, pcret *re, pcret_extra *extra, TCHAR output_mode, Var &output_var, int *offset, int pattern_count, int captured_pattern_count, LPTSTR &mem_to_free) { // OTHERWISE, CONTINUE ON TO STORE THE SUBSTRINGS THAT MATCHED THE SUBPATTERNS (EVEN IF PCRE_ERROR_NOMATCH). // 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, IsPureNumeric() 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". if (output_mode == 'O') { LPTSTR mark = (extra->flags & PCRE_EXTRA_MARK) ? (LPTSTR)*extra->mark : NULL; IObject *m = RegExMatchObject::Create(haystack, offset, subpat_name, pattern_count, captured_pattern_count, (LPTSTR) mark); if (m) output_var.AssignSkipAddRef(m); else output_var.Assign(); return; } // Make var_name longer than Max so that FindOrAddVar() will be able to spot and report var names // that are too long, either because the base-name is too long, or the name becomes too long // as a result of appending the array index number: TCHAR var_name[MAX_VAR_NAME_LENGTH + 68]; // Allow +3 extra for "Len" and "Pos" suffixes, +1 for terminator, and +64 for largest sub-pattern name (actually it's 32, but 64 allows room for future expansion). 64 is also enough room for the largest 64-bit integer, 20 chars: 18446744073709551616 _tcscpy(var_name, output_var.mName); // This prefix is copied in only once, for performance. size_t suffix_length, prefix_length = _tcslen(var_name); LPTSTR var_name_suffix = var_name + prefix_length; // The position at which to copy the sequence number (index). int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; int n, p = 1, *this_offset = offset + 2; // Init for both loops below. Var *array_item; bool subpat_not_matched; int subpat_pos, subpat_len; if (output_mode == 'P') { for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // See comments in similar section below about this. if (subpat_not_matched) { subpat_pos = 0; subpat_len = 0; } else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; ++subpat_pos; // One-based (i.e. position zero means "not found"). } if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { const LPCTSTR &the_subpat_name = subpat_name[p]; suffix_length = _stprintf(var_name_suffix, _T("Pos%s"), the_subpat_name); // Append the subpattern to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); suffix_length = _stprintf(var_name_suffix, _T("Len%s"), the_subpat_name); // Append the subpattern name to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); // It seemed more convenient for scripts to store Length instead of an ending offset. // Fix for v1.0.45.01: Section below added. See similar section further below for comments. if (!subpat_not_matched && allow_dupe_subpat_names) // Explicitly check subpat_not_matched not pos/len so that behavior is consistent with the default mode (non-position). for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so write it out as its pattern number instead. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { // For comments about this section, see the similar for-loop later below. suffix_length = _stprintf(var_name_suffix, _T("Pos%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_pos); //else var couldn't be created: no error reporting currently, since it basically should never happen. suffix_length = _stprintf(var_name_suffix, _T("Len%d"), p); // Append the element number to the array's base name. if (array_item = g_script.FindOrAddVar(var_name, prefix_length + suffix_length, always_use)) array_item->Assign(subpat_len); } } //goto free_and_return; return; } // if (output_mode == 'P') // Otherwise, we're in get-substring mode (not offset mode), so store the substring that matches each subpattern. for (; p < pattern_count; ++p, this_offset += 2) // Start at 1 because above already did pattern #0 (the full pattern). { // If both items in this_offset are -1, that means the substring wasn't populated because it's // subpattern wasn't needed to find a match (or there was no match for *anything*). For example: // "(xyz)|(abc)" (in which only one is subpattern will match). // NOTE: PCRE isn't clear on this, but it seems likely that captured_pattern_count // (returned from pcre_exec()) can be less than pattern_count (from pcre_fullinfo/ // PCRE_INFO_CAPTURECOUNT). So the below takes this into account by not trusting values // in offset[] that are beyond captured_pattern_count. Further evidence of this is PCRE's // pcre_copy_substring() function, which consults captured_pattern_count to decide whether to // consult the offset array. The formula below works even if captured_pattern_count==PCRE_ERROR_NOMATCH. subpat_not_matched = (p >= captured_pattern_count || this_offset[0] < 0); // Relies on short-circuit boolean order. if (subpat_name && subpat_name[p]) // This subpattern number has a name, so store it under that name. { if (*subpat_name[p]) // This check supports allow_dupe_subpat_names. See comments below. { // This section is similar to the one in the "else" below, so see it for more comments. _tcscpy(var_name_suffix, subpat_name[p]); // Append the subpat name to the array's base name. _tcscpy() seems safe because PCRE almost certainly enforces the 32-char limit on subpattern names. if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); // Fix for v1.0.45.01: When the J option (allow duplicate named subpatterns) is in effect, // PCRE returns entries for all the duplicates. But we don't want an unmatched duplicate // to overwrite a previously matched duplicate. To prevent this, when we're here (i.e. // this subpattern matched something), mark duplicate entries in the names array that lie // to the right of this item to indicate that they should be skipped by subsequent iterations. if (allow_dupe_subpat_names) for (n = p + 1; n < pattern_count; ++n) // Search to the right of this subpat to find others with the same name. if (subpat_name[n] && !_tcsicmp(subpat_name[n], subpat_name[p])) // Case-insensitive because unlike PCRE, named subpatterns conform to AHK convention of insensitive variable names. subpat_name[n] = _T(""); // Empty string signals subsequent iterations to skip it entirely. } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } //else an empty subpat name caused by "allow duplicate names". Do nothing (see comments above). } else // This subpattern has no name, so instead write it out as its actual pattern number. For performance and memory utilization, it seems best to store only one or the other (named or number), not both. { _itot(p, var_name_suffix, 10); // Append the element number to the array's base name. // To help performance (in case the linked list of variables is huge), tell it where // to start the search. Use the base array name rather than the preceding element because, // for example, Array19 is alphabetically less than Array2, so we can't rely on the // numerical ordering: if (array_item = g_script.FindOrAddVar(var_name, 0, always_use)) { if (p < pattern_count-1 // i.e. there's at least one more subpattern after this one (if there weren't, making a copy of haystack wouldn't be necessary because overlap can't harm this final assignment). && haystack == array_item->Contents(FALSE)) // For more comments, see similar section in BIF_RegEx. if (mem_to_free = _tcsdup(haystack)) haystack = mem_to_free; if (subpat_not_matched) array_item->Assign(); // Omit all parameters to make the var empty without freeing its memory (for performance, in case this RegEx is being used many times in a loop). else { subpat_pos = this_offset[0]; subpat_len = this_offset[1] - subpat_pos; array_item->Assign(haystack + subpat_pos, subpat_len); } } //else var couldn't be created: no error reporting currently, since it basically should never happen. } } // for() each subpattern. } RegExMatchObject *RegExMatchObject::Create(LPCTSTR aHaystack, int *aOffset, LPCTSTR *aPatternName , int aPatternCount, int aCapturedPatternCount, LPCTSTR aMark) { // If there was no match, seems best to not return an object: if (aCapturedPatternCount < 1) return NULL; RegExMatchObject *m = new RegExMatchObject(); if (!m) return NULL; if ( aMark && !(m->mMark = _tcsdup(aMark)) ) { m->Release(); return NULL; } 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; // Copy haystack. Must copy the whole haystack since it is possible (though rare) for a // subpattern to precede the overall match - for instance, if \K is used or a subpattern // is captured inside a look-behind assertion. if ( !(m->mHaystack = _tcsdup(aHaystack)) // Allocate memory for a copy of the offset array. || !(m->mOffset = (int *)malloc(aPatternCount * 2 * sizeof(int *))) ) { m->Release(); // This also frees m->mHaystack if it is non-NULL. return NULL; } int p, i, pos, len; // Convert start/end offsets to offset and length. for (p = 0, i = 0; p < aCapturedPatternCount; ++p) { if (aOffset[i] < 0) { pos = -1; len = 0; } else { pos = aOffset[i]; len = aOffset[i+1] - pos; } m->mOffset[i++] = pos; m->mOffset[i++] = len; } // Initialize the remainder of the offset vector (patterns which were not captured): for ( ; p < aPatternCount; ++p) { m->mOffset[i++] = -1; m->mOffset[i++] = 0; } // Copy subpattern names. if (aPatternName) { // Allocate array of pointers. if ( !(m->mPatternName = (LPTSTR *)malloc(aPatternCount * sizeof(LPTSTR *))) ) { m->Release(); return NULL; } // Copy names and initialize array. m->mPatternName[0] = NULL; for (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
tinku99/ahkdll
f7c294fd91b186d368f93fc3cab727b2b5c35f97
Changed default SendMode to SM_Input
diff --git a/source/defines.h b/source/defines.h index 01bc906..feb9762 100644 --- a/source/defines.h +++ b/source/defines.h @@ -273,602 +273,602 @@ struct ExprTokenType // Something in the compiler hates the name TokenType, so size_t marker_length; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; }; }; // Note that marker's str-length should not be stored in this struct, even though it might be readily // available in places and thus help performance. This is because if it were stored and the marker // or SYM_VAR's var pointed to a location that was changed as a side effect of an expression's // call to a script function, the length would then be invalid. SymbolType symbol; // Short-circuit benchmark is currently much faster with this and the next beneath the union, perhaps due to CPU optimizations for 8-byte alignment. union { ExprTokenType *circuit_token; // Facilitates short-circuit boolean evaluation. LPTSTR mem_to_free; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; // The above two probably need to be adjacent to each other to conserve memory due to 8-byte alignment, // which is the default alignment (for performance reasons) in any struct that contains 8-byte members // such as double and __int64. }; #define MAX_TOKENS 512 // Max number of operators/operands. Seems enough to handle anything realistic, while conserving call-stack space. #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. // 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_ASSIGN, ACT_ASSIGNEXPR, ACT_EXPRESSION, ACT_ADD, ACT_SUB, ACT_MULT, ACT_DIV , ACT_ASSIGN_FIRST = ACT_ASSIGN, ACT_ASSIGN_LAST = ACT_DIV , ACT_REPEAT // Never parsed directly, only provided as a translation target for the old command (see other notes). , ACT_ELSE // Parsed at a lower level than most commands to support same-line ELSE-actions (e.g. "else if"). , ACT_IFIN, ACT_IFNOTIN, ACT_IFCONTAINS, ACT_IFNOTCONTAINS, ACT_IFIS, ACT_IFISNOT , ACT_IFBETWEEN, ACT_IFNOTBETWEEN , ACT_IFEXPR // i.e. if (expr) // *** *** *** KEEP ALL OLD-STYLE/AUTOIT V2 IFs AFTER THIS (v1.0.20 bug fix). *** *** *** , ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // ACT_IS_IF_OLD() relies upon ACT_IFEQUAL through ACT_IFLESSOREQUAL being adjacent to one another // and it relies upon the fact that ACT_IFEQUAL is first in the series and ACT_IFLESSOREQUAL last. , ACT_IFEQUAL = ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION, ACT_IFNOTEQUAL, ACT_IFGREATER, ACT_IFGREATEROREQUAL , ACT_IFLESS, ACT_IFLESSOREQUAL , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes. , ACT_IFWINEXIST = ACT_FIRST_COMMAND , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE , ACT_IFINSTRING, ACT_IFNOTINSTRING , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX // Keep this range updated with any new IFs that are added. , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE , ACT_GETKEYSTATE , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS , ACT_STATUSBARGETTEXT , ACT_STATUSBARWAIT , ACT_CLIPWAIT, ACT_KEYWAIT , ACT_SLEEP, ACT_RANDOM , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_CONTINUE // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_TRY, ACT_CATCH, ACT_THROW , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE , ACT_WINHIDE, ACT_WINSHOW , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE // Keep rarely used actions near the bottom for parsing/performance reasons: , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME , ACT_FILEGETSIZE, ACT_FILEGETVERSION , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_SETREGVIEW , ACT_OUTPUTDEBUG , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME , ACT_SUSPEND, ACT_PAUSE , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET , ACT_EXITAPP , ACT_SHUTDOWN , ACT_FILEENCODING // Make these the last ones before the count so they will be less often processed. This helps // performance because this one doesn't actually have a keyword so will never result // in a match anyway. UPDATE: No longer used because Run/RunWait is now required, which greatly // improves syntax checking during load: //, ACT_EXEC // It's safer to use g_ActionCount, which is calculated immediately after the array is declared // and initialized, at which time we know its true size. However, the following lets us detect // when the size of the array doesn't match the enum (in debug mode): #ifdef _DEBUG , ACT_COUNT #endif }; enum enum_act_old { OLD_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order: , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL , OLD_LEFTCLICK, OLD_RIGHTCLICK, OLD_LEFTCLICKDRAG, OLD_RIGHTCLICKDRAG , OLD_HIDEAUTOITWIN, OLD_REPEAT, OLD_ENDREPEAT , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS }; // It seems best not to include ACT_SUSPEND in the below, since the user may have marked // a large number of subroutines as "Suspend, Permit". Even PAUSE is iffy, since the user // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey // was 1 (the default). #ifndef MINIDLL #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \ || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS) #else #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_RELOAD) #endif #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance. #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF) #define ACT_IS_IF_OR_ELSE_OR_LOOP(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ActionType == ACT_LOOP || ActionType == ACT_WHILE || ActionType == ACT_FOR) #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \ && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL)) // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new") // can support parameters on the same line or on the next line. For example, both of the above are allowed: // IfMsgBox, No, Gosub, XXX // IfMsgBox, No // Gosub, XXX // 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 // 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. #ifndef MINIDLL #define MAX_INPUTBOXES 4 #define MAX_PROGRESS_WINDOWS 10 // Allow a lot for downloads and such. #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above. #define MAX_SPLASHIMAGE_WINDOWS 10 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above. #endif #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. #ifndef MINIDLL #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #endif #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. #ifndef MINIDLL #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #endif #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. #ifndef MINIDLL // 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 #endif #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 CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close() #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; // Just make them int's, rather than something smaller, because the collection // of actions will take up very little memory. Int's are probably faster // for the processor to access since they are the native word size, or something: // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform() // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for // non-AutoIt2 scripts, such as the extra ones in StringGetPos). // Also, changing these from ints to chars greatly reduces 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, MaxParamsAu2WithHighBit; // Array indicating which args must be purely numeric. The first arg is // number 1, the second 2, etc (i.e. it doesn't start at zero). The list // is ended with a zero, much like a string. The compiler will notify us // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased: #define MAX_NUMERIC_PARAMS 7 ActionTypeType NumericParams[MAX_NUMERIC_PARAMS]; }; #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}; #ifndef MINIDLL 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("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")} enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely). , GUI_EVENT_RCLK, GUI_EVENT_COLCLK , GUI_EVENT_FIRST_UNNAMED // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below. , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield). #endif typedef USHORT CoordModeType; // Bit-field offsets: #ifndef MINIDLL #define COORD_MODE_PIXEL 0 #endif #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #ifndef MINIDLL #define COORD_MODE_MENU 8 #endif #define COORD_MODE_WINDOW 0 #define COORD_MODE_CLIENT 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #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; } // Same reason as above struct. It's best to keep this struct as small as possible // because it's used as a local (stack) var by at least one recursive function: // Each instance of this struct generally corresponds to a quasi-thread. The function that creates // a new thread typically saves the old thread's struct values on its stack so that they can later // be copied back into the g struct when the thread is resumed: class Func; // Forward declarations struct FuncAndToken { ExprTokenType mToken ; LPTSTR result_to_return_dll; Func * mFunc ; VARIANT variant_to_return_dll; LPTSTR param[10]; BYTE mParamCount; }; class Label; // class Line; // struct RegItemStruct; // struct LoopReadFileStruct; // #ifndef MINIDLL class GuiType; // #endif struct global_struct { // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious). __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values. __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. WIN32_FIND_DATA *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. // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class // because they're more appropriate as thread-attributes rather than being global to the entire script. TitleMatchModes TitleMatchMode; int IntervalBeforeRest; int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible. int Priority; // This thread's priority relative to others. DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. #ifndef MINIDLL GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click. #endif EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard. #ifndef MINIDLL POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed. GuiType *GuiWindow; // The GUI window that launched this thread. GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..." GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid. GuiType *DialogOwner; // This thread's GUI owner, if any. GuiIndexType GuiControlIndex; // The GUI control index that launched this thread. #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL) #endif 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; // TCHAR FormatFloat[32]; Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine. Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. //HWND hWndToRestore; int MsgBoxResult; // Which button was pressed in the most recent MsgBox. HWND DialogHWND; DWORD RegView; // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: SendModes SendMode; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. DWORD ThreadStartTime; int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too). bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness. 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 AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. 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; CoordModeType CoordMode; // Bitwise collection of flags. UCHAR StringCaseSense; // On/Off/Locale bool StoreCapslockMode; bool AutoTrim; char FormatInt; SendLevelType SendLevel; bool MsgBoxTimedOut; // Doesn't require initialization. bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle". bool ListLinesIsEnabled; UINT Encoding; ExprTokenType* ThrownToken; Line* ExcptLine; bool InTryBlock; }; inline void global_maximize_interruptibility(global_struct &g) { g.AllowThreadToBeInterrupted = true; g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.ThreadIsCritical = false; g.AllowTimers = true; #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. } inline void global_clear_state(global_struct &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 ErrorLevel shouldn't). { g.CurrentFunc = NULL; g.CurrentFuncGosub = NULL; g.CurrentLabel = NULL; g.hWndLastUsed = NULL; //g.hWndToRestore = NULL; g.MsgBoxResult = 0; g.IsPaused = false; g.UninterruptedLineCount = 0; #ifndef MINIDLL g.DialogOwner = NULL; #endif g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true. #ifndef MINIDLL g.GuiDefaultWindow = NULL; #endif // Above line is done because allowing it to be permanently changed by the auto-exec section // seems like it would cause more confusion that it's worth. A change to the global default // or even an override/always-use-this-window-number mode can be added if there is ever a // demand for it. 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.InTryBlock = false; } inline void global_init(global_struct &g) // This isn't made a real constructor to avoid the overhead, since there are times when we // want to declare a local var of type global_struct without having it initialized. { // 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: global_clear_state(g); - g.SendMode = SM_INPUT_FALLBACK_TO_PLAY; // v1.1.7.3: Default to SM_INPUT_FALLBACK_TO_PLAY for best performance. + g.SendMode = SM_INPUT; g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3. 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. // Not sure what the optimal default is. 1 seems too low (scripts would be very slow by default): g.LinesPerCycle = -1; g.IntervalBeforeRest = 10; // sleep for 10ms every 10ms #define DEFAULT_PEEK_FREQUENCY 5 g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL. g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values. g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.AllowTimers = true; g.ThreadIsCritical = false; g.Priority = 0; g.LastError = 0; #ifndef MINIDLL g.GuiEvent = GUI_EVENT_NONE; #endif g.EventInfo = NO_EVENT_INFO; #ifndef MINIDLL g.GuiPoint.x = COORD_UNSPECIFIED; g.GuiPoint.y = COORD_UNSPECIFIED; // For these, indexes rather than pointers are stored because handles can become invalid during the // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself): g.GuiWindow = NULL; g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds. g.GuiDefaultWindow = NULL; #endif 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.StringCaseSense = SCS_INSENSITIVE; // AutoIt2 default, and it does seem best. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.AutoTrim = true; // AutoIt2's default, and overall the best default in most cases. _tcscpy(g.FormatFloat, _T("%0.6f")); g.FormatInt = 'D'; g.SendLevel = 0; g.ListLinesIsEnabled = true; g.Encoding = CP_ACP; // For FormatFloat: // I considered storing more than 6 digits to the right of the decimal point (which is the default // for most Unices and MSVC++ it seems). But going beyond that makes things a little weird for many // numbers, due to the inherent imprecision of floating point storage. For example, 83648.4 divided // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with // 20 digits. The extra zeros could be chopped off the end easily enough, but even so, going beyond // 6 digits seems to do more harm than good for the avg. user, overall. A default of 6 is used here // in case other/future compilers have a different default (for backward compatibility, we want // 6 to always be in effect as the default for future releases). } #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel. #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) // 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 diff --git a/source/globaldata.cpp b/source/globaldata.cpp index 49498b8..d4d98e1 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,698 +1,698 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() HINSTANCE g_hInstance = NULL; // Set by WinMain(). DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; UINT g_DefaultScriptCodepage = CP_ACP; bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_AllowSameLineComments = true; bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. -SendModes g_HSSendMode = SM_INPUT_FALLBACK_TO_PLAY; // v1.1.7.03: New default for more reliable hotstrings and best performance. +SendModes g_HSSendMode = SM_INPUT; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} // This command is never directly parsed, but we need to have it here as a translation // target for the old "repeat" command. This is because that command treats a zero // first-param as an infinite loop. Since that param can be a dereferenced variable, // there's no way to reliably translate each REPEAT command into a LOOP command at // load-time. Thus, we support both types of loops as actual commands that are // handled separately at runtime. , {_T("Repeat"), 0, 1, 1, {1, 0}} // Iteration Count: was mandatory in AutoIt2 but doesn't seem necessary here. , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("Continue"), 0, 1, 1, NULL} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {_T("IniRead"), 2, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) , {_T("IniWrite"), 3, 4, 4, NULL} // Value, Filespec, Section, Key , {_T("IniDelete"), 2, 3, 3, NULL} // Filespec, Section, Key // These require so few parameters due to registry loops, which provide the missing parameter values // automatically. In addition, RegRead can't require more than 1 param since the 2nd param is // an option/obsolete parameter: , {_T("RegRead"), 1, 5, 5 H, NULL} // output var, (ValueType [optional]), RegKey, RegSubkey, ValueName , {_T("RegWrite"), 0, 5, 5, NULL} // ValueType, RegKey, RegSubKey, ValueName, Value (set to blank if omitted?) , {_T("RegDelete"), 0, 3, 3, NULL} // RegKey, RegSubKey, ValueName , {_T("SetRegView"), 1, 1, 1, NULL} , {_T("OutputDebug"), 1, 1, 1, NULL} , {_T("SetKeyDelay"), 0, 3, 3, {1, 2, 0}} // Delay in ms (numeric, negative allowed), PressDuration [, Play] , {_T("SetMouseDelay"), 1, 2, 2, {1, 0}} // Delay in ms (numeric, negative allowed) [, Play] , {_T("SetWinDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetControlDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetBatchLines"), 1, 1, 1, NULL} // Can be non-numeric, such as 15ms, or a number (to indicate line count). , {_T("SetTitleMatchMode"), 1, 1, 1, NULL} // Allowed values: 1, 2, slow, fast , {_T("SetFormat"), 2, 2, 2, NULL} // Float|Integer, FormatString (for float) or H|D (for int) , {_T("FormatTime"), 1, 3, 3 H, NULL} // OutputVar, YYYYMMDDHH24MISS, Format (format is last to avoid having to escape commas in it). , {_T("Suspend"), 0, 1, 1, NULL} // On/Off/Toggle/Permit/Blank (blank is the same as toggle) , {_T("Pause"), 0, 2, 2, NULL} // On/Off/Toggle/Blank (blank is the same as toggle), AlwaysAffectUnderlying , {_T("AutoTrim"), 1, 1, 1, NULL} // On/Off , {_T("StringCaseSense"), 1, 1, 1, NULL} // On/Off/Locale , {_T("DetectHiddenWindows"), 1, 1, 1, NULL} // On/Off , {_T("DetectHiddenText"), 1, 1, 1, NULL} // On/Off , {_T("BlockInput"), 1, 1, 1, NULL} // On/Off , {_T("SetNumlockState"), 0, 1, 1, NULL} // On/Off/AlwaysOn/AlwaysOff or blank (unspecified) to return to normal. , {_T("SetScrollLockState"), 0, 1, 1, NULL} // same , {_T("SetCapslockState"), 0, 1, 1, NULL} // same , {_T("SetStoreCapslockMode"), 1, 1, 1, NULL} // On/Off , {_T("KeyHistory"), 0, 2, 2, NULL}, {_T("ListLines"), 0, 1, 1, NULL} , {_T("ListVars"), 0, 0, 0, NULL}, {_T("ListHotkeys"), 0, 0, 0, NULL} , {_T("Edit"), 0, 0, 0, NULL} , {_T("Reload"), 0, 0, 0, NULL} , {_T("Menu"), 2, 6, 6, NULL} // tray, add, name, label, options, future use , {_T("Gui"), 1, 4, 4, NULL} // Cmd/Add, ControlType, Options, Text , {_T("GuiControl"), 0, 3, 3 H, NULL} // Sub-cmd (defaults to "contents"), ControlName/ID, Text , {_T("GuiControlGet"), 1, 4, 4, NULL} // OutputVar, Sub-cmd (defaults to "contents"), ControlName/ID (defaults to control assoc. with OutputVar), Text/FutureUse , {_T("ExitApp"), 0, 1, 1, {1, 0}} // Optional exit-code. v1.0.48.01: Allow an expression like ACT_EXIT does. , {_T("Shutdown"), 1, 1, 1, {1, 0}} // Seems best to make the first param (the flag/code) mandatory. , {_T("FileEncoding"), 0, 1, 1, NULL} }; // Below is the most maintainable way to determine the actual count? // Due to C++ lang. restrictions, can't easily make this a const because constants // automatically get static (internal) linkage, thus such a var could never be // used outside this module: int g_ActionCount = _countof(g_act); Action g_old_act[] = { {_T(""), 0, 0, 0, NULL} // OLD_INVALID. , {_T("SetEnv"), 1, 2, 2, NULL} , {_T("EnvAdd"), 2, 3, 3, {2, 0}}, {_T("EnvSub"), 1, 3, 3, {2, 0}} // EnvSub (but not Add) allow 2nd to be blank due to 3rd param. , {_T("EnvMult"), 2, 2, 2, {2, 0}}, {_T("EnvDiv"), 2, 2, 2, {2, 0}} , {_T("IfEqual"), 1, 2, 2, NULL}, {_T("IfNotEqual"), 1, 2, 2, NULL} , {_T("IfGreater"), 1, 2, 2, NULL}, {_T("IfGreaterOrEqual"), 1, 2, 2, NULL} , {_T("IfLess"), 1, 2, 2, NULL}, {_T("IfLessOrEqual"), 1, 2, 2, NULL} , {_T("LeftClick"), 2, 2, 2, {1, 2, 0}}, {_T("RightClick"), 2, 2, 2, {1, 2, 0}} , {_T("LeftClickDrag"), 4, 4, 4, {1, 2, 3, 4, 0}}, {_T("RightClickDrag"), 4, 4, 4, {1, 2, 3, 4, 0}} , {_T("HideAutoItWin"), 1, 1, 1, NULL} // Allow zero params, unlike AutoIt. These params should match those for REPEAT in the above array: , {_T("Repeat"), 0, 1, 1, {1, 0}}, {_T("EndRepeat"), 0, 0, 0, NULL} , {_T("WinGetActiveTitle"), 1, 1, 1, NULL} // <Title Var> , {_T("WinGetActiveStats"), 5, 5, 5, NULL} // <Title Var>, <Width Var>, <Height Var>, <Xpos Var>, <Ypos Var> }; int g_OldActionCount = _countof(g_old_act); key_to_vk_type g_key_to_vk[] = { {_T("Numpad0"), VK_NUMPAD0} , {_T("Numpad1"), VK_NUMPAD1} , {_T("Numpad2"), VK_NUMPAD2} , {_T("Numpad3"), VK_NUMPAD3} , {_T("Numpad4"), VK_NUMPAD4} , {_T("Numpad5"), VK_NUMPAD5} , {_T("Numpad6"), VK_NUMPAD6} , {_T("Numpad7"), VK_NUMPAD7} , {_T("Numpad8"), VK_NUMPAD8} , {_T("Numpad9"), VK_NUMPAD9} , {_T("NumpadMult"), VK_MULTIPLY} , {_T("NumpadDiv"), VK_DIVIDE} , {_T("NumpadAdd"), VK_ADD} , {_T("NumpadSub"), VK_SUBTRACT} // , {_T("NumpadEnter"), VK_RETURN} // Must do this one via scan code, see below for explanation. , {_T("NumpadDot"), VK_DECIMAL} , {_T("Numlock"), VK_NUMLOCK} , {_T("ScrollLock"), VK_SCROLL} , {_T("CapsLock"), VK_CAPITAL} , {_T("Escape"), VK_ESCAPE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Esc"), VK_ESCAPE} , {_T("Tab"), VK_TAB} , {_T("Space"), VK_SPACE} , {_T("Backspace"), VK_BACK} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("BS"), VK_BACK} // These keys each have a counterpart on the number pad with the same VK. Use the VK for these, // since they are probably more likely to be assigned to hotkeys (thus minimizing the use of the // keyboard hook, and use the scan code (SC) for their counterparts. UPDATE: To support handling // these keys with the hook (i.e. the sc_takes_precedence flag in the hook), do them by scan code // instead. This allows Numpad keys such as Numpad7 to be differentiated from NumpadHome, which // would otherwise be impossible since both of them share the same scan code (i.e. if the // sc_takes_precedence flag is set for the scan code of NumpadHome, that will effectively prevent // the hook from telling the difference between it and Numpad7 since the hook is currently set // to handle an incoming key by either vk or sc, but not both. // Even though ENTER is probably less likely to be assigned than NumpadEnter, must have ENTER as // the primary vk because otherwise, if the user configures only naked-NumPadEnter to do something, // RegisterHotkey() would register that vk and ENTER would also be configured to do the same thing. , {_T("Enter"), VK_RETURN} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Return"), VK_RETURN} , {_T("NumpadDel"), VK_DELETE} , {_T("NumpadIns"), VK_INSERT} , {_T("NumpadClear"), VK_CLEAR} // same physical key as Numpad5 on most keyboards? , {_T("NumpadUp"), VK_UP} , {_T("NumpadDown"), VK_DOWN} , {_T("NumpadLeft"), VK_LEFT} , {_T("NumpadRight"), VK_RIGHT} , {_T("NumpadHome"), VK_HOME} , {_T("NumpadEnd"), VK_END} , {_T("NumpadPgUp"), VK_PRIOR} , {_T("NumpadPgDn"), VK_NEXT} , {_T("PrintScreen"), VK_SNAPSHOT} , {_T("CtrlBreak"), VK_CANCEL} // Might want to verify this, and whether it has any peculiarities. , {_T("Pause"), VK_PAUSE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Break"), VK_PAUSE} // Not really meaningful, but kept for as a synonym of Pause for backward compatibility. See CtrlBreak. , {_T("Help"), VK_HELP} // VK_HELP is probably not the extended HELP key. Not sure what this one is. , {_T("Sleep"), VK_SLEEP} , {_T("AppsKey"), VK_APPS} // UPDATE: For the NT/2k/XP version, now doing these by VK since it's likely to be // more compatible with non-standard or non-English keyboards: , {_T("LControl"), VK_LCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("RControl"), VK_RCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("LCtrl"), VK_LCONTROL} // Abbreviated versions of the above. , {_T("RCtrl"), VK_RCONTROL} // , {_T("LShift"), VK_LSHIFT} , {_T("RShift"), VK_RSHIFT} , {_T("LAlt"), VK_LMENU} , {_T("RAlt"), VK_RMENU} // These two are always left/right centric and I think their vk's are always supported by the various // Windows API calls, unlike VK_RSHIFT, etc. (which are seldom supported): , {_T("LWin"), VK_LWIN} , {_T("RWin"), VK_RWIN} // The left/right versions of these are handled elsewhere since their virtual keys aren't fully API-supported: , {_T("Control"), VK_CONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Ctrl"), VK_CONTROL} // An alternate for convenience. , {_T("Alt"), VK_MENU} , {_T("Shift"), VK_SHIFT} /* These were used to confirm the fact that you can't use RegisterHotkey() on VK_LSHIFT, even if the shift modifier is specified along with it: , {_T("LShift"), VK_LSHIFT} , {_T("RShift"), VK_RSHIFT} */
tinku99/ahkdll
ef154975fa1261c3a0fd200b9cbf5ed525bed25c
Fixed a bug in Script::Init
diff --git a/source/script.cpp b/source/script.cpp index 20d900d..90fdaa4 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,1009 +1,1010 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, 0); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mIsAutoIt2(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); g_SoundWasPlayed = 0; } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { /* //ExprTokenType aResultToken; static ExprTokenType **aParam = (ExprTokenType **)SimpleHeap::Malloc(sizeof(__int64));; ExprTokenType aThisParam[1]; aThisParam[0].symbol = SYM_STRING; aThisParam[0].marker = _T(""); aParam[0] = aThisParam; int aParamCount = 0; BIF_DynaCall(aThisParam[0], aParam, aParamCount); */ // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible. int v, i; g_script.mIsReadyToExecute = false; for (v = 0; v < mVarCount; ++v) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; mVar[v]->ConvertToNonAliasIfNecessary(); //if (!_tcsicmp(mVar[v]->mName,_T("Args"))) // if we restart args are filled again anyway ??? // continue; mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; ++v) { mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) { f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mStaticVarCount; ++v) { f.mStaticVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; ++v) { f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } for (v = 0; v < f.mStaticLazyVarCount; ++v) { f.mStaticLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mStaticLazyVar[v]->Free(); } delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel; label != NULL;label = label->mNextLabel) { Label *nextLabel = label->mNextLabel; label->mJumpToLine = NULL; label->mName = _T(""); label->mPrevLabel = NULL; } for (Line *line = g_script.mLastLine; line;) { Line *nextLine = line->mPrevLine; delete line; line = nextLine; } mFuncCount = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; #ifndef MINIDLL mFirstMenu = NULL; #endif mFirstTimer = NULL; mIsReadyToExecute = false; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; //reset count for OnMessage if (g_MsgMonitor) free(g_MsgMonitor); g_MsgMonitorCount = 0; g_MsgMonitor = NULL; g_nMessageBoxes = 0; #ifndef MINIDLL g_nInputBoxes = 0; g_nFileDialogs = 0; g_nFolderDialogs = 0; #endif for(i=1;Line::sSourceFileCount>i;i++) // first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; // free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } #ifndef MINIDLL AddRemoveHooks(0); Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif Script::~Script(); global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path in front to make sure we have a valid path anyway GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); if (pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, //&commandLineContents, CommanLineLength, NULL)) { int dllargc = 0; TCHAR *param; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca(pbi.PebBaseAddress->ProcessParameters->CommandLine.Length); #endif LPWSTR *dllargv = CommandLineToArgvW(pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer,&dllargc); if (dllargc > 1 && pbi.PebBaseAddress->ProcessParameters->CommandLine.Length) // Only process if parameters were given { for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) continue; else // since this is not a switch, the end of the [Switches] section has been reached (by design). { if (GetFileAttributes(param) == 0xFFFFFFFF) { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else { - _tcscpy(buf,param); + if (!GetFullPathName(param, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. + return FAIL; } break; // No more switches allowed after this point. } } } } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. size_t filename_length = _tcslen(filename_marker); #ifndef _USRDLL if ( mIsAutoIt2 = (filename_length >= 4 && !_tcsicmp(filename_marker + filename_length - 4, EXT_AUTOIT2)) ) { // Set the old/AutoIt2 defaults for maximum safety and compatibility. // Standalone EXEs (compiled scripts) are always considered to be non-AutoIt2 (otherwise, // the user should probably be using the AutoIt2 compiler). g_AllowSameLineComments = false; g_EscapeChar = '\\'; g.TitleFindFast = true; // In case the normal default is false. g.DetectHiddenText = false; // Make the mouse fast like AutoIt2, but not quite insta-move. 2 is expected to be more // reliable than 1 since the AutoIt author said that values less than 2 might cause the // drag to fail (perhaps just for specific apps, such as games): g.DefaultMouseSpeed = 2; g.KeyDelay = 20; g.WinDelay = 500; g.LinesPerCycle = 1; g.IntervalBeforeRest = -1; // i.e. this method is disabled by default for AutoIt2 scripts. // Reduce max params so that any non escaped delimiters the user may be using literally // in "window text" will still be considered literal, rather than as delimiters for // args that are not supported by AutoIt2, such as exclude-title, exclude-text, MsgBox // timeout, etc. Note: Don't need to change IfWinExist and such because those already // have special handling to recognize whether exclude-title is really a valid command // instead (e.g. IfWinExist, title, text, Gosub, something). // NOTE: DO NOT ADD the IfWin command series to this section, since there is special handling // for parsing those commands to figure out whether they're being used in the old AutoIt2 // style or the new Exclude Title/Text mode. // v1.0.40.02: The following is no longer done because a different mechanism is required now // that the ARGn macros do not check whether mArgc is too small and substitute an empty string // (instead, there is a loop in ExpandArgs that puts an empty string in each sArgDeref entry // for which the script omitted a parameter [and that loop relies on MaxParams being absolutely // accurate rather than conditional upon whether the script is of type ".aut"]). //g_act[ACT_FILESELECTFILE].MaxParams -= 2; //g_act[ACT_FILEREMOVEDIR].MaxParams -= 1; //g_act[ACT_MSGBOX].MaxParams -= 1; //g_act[ACT_INIREAD].MaxParams -= 1; //g_act[ACT_STRINGREPLACE].MaxParams -= 1; //g_act[ACT_STRINGGETPOS].MaxParams -= 2; //g_act[ACT_WINCLOSE].MaxParams -= 3; // -3 for these two, -2 for the others. //g_act[ACT_WINKILL].MaxParams -= 3; //g_act[ACT_WINACTIVATE].MaxParams -= 2; //g_act[ACT_WINMINIMIZE].MaxParams -= 2; //g_act[ACT_WINMAXIMIZE].MaxParams -= 2; //g_act[ACT_WINRESTORE].MaxParams -= 2; //g_act[ACT_WINHIDE].MaxParams -= 2; //g_act[ACT_WINSHOW].MaxParams -= 2; //g_act[ACT_WINSETTITLE].MaxParams -= 2; //g_act[ACT_WINGETTITLE].MaxParams -= 2; } #endif if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if ( !(g_array = (global_struct *)realloc(g_array,(g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "background thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT); return OK; } #ifndef MINIDLL
tinku99/ahkdll
41031aa092454dea9c964cfd744487df987b7aad
Fixed allocation bug for ahkFunction and ahkPostFunction
diff --git a/source/exports.cpp b/source/exports.cpp index f7a156d..d11e509 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,750 +1,749 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(int timeout){return ahkTerminate(timeout);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { - result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + sizeof(TCHAR)); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { - result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength + sizeof(TCHAR)); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i < 10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); return 0; } else { FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; for (int i = 0;i < aParamsCount;i++) { - aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],_tcslen(*params[i])*sizeof(WCHAR)); + aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],(_tcslen(*params[i])+1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken.param[i],*params[i]); } //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mStaticVar, func.mStaticVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); g_script.PreprocessLocalVars(func, func.mStaticLazyVar, func.mStaticLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i<10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); switch (aResultToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aResultToken.var->Contents())) { - result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.var->Contents())*sizeof(TCHAR)); + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aResultToken.var->Contents()) + 1)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aResultToken.marker)) { - result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.marker)*sizeof(TCHAR)); + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(_tcslen(aResultToken.marker) + 1)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aResultToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); } return result_to_return_dll; } else // UDF { //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; for (int i = 0;i < aParamsCount;i++) { - aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],_tcslen(*params[i])*sizeof(WCHAR)); + aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],(_tcslen(*params[i]) + 1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken.param[i],*params[i]); } aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); for (int aParamCount = 0;func.mParamCount > aParamCount && aFuncAndToken->mParamCount > aParamCount;aParamCount++) func.mParam[aParamCount].var->AssignString(aFuncAndToken->param[aParamCount]); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { - aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); + aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.var->Contents()) + 1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { - aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); + aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,(_tcslen(aFuncAndToken->mToken.marker) + 1)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { - Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { VARIANT *variants[10]; int aParamCount = 0; variants[0]=&param1;variants[1]=&param2;variants[2]=&param3;variants[3]=&param4;variants[4]=&param5; variants[5]=&param6;variants[6]=&param7;variants[7]=&param8;variants[8]=&param9;variants[9]=&param10; if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_VAR; aParam[aParamCount]->var = (Var*)alloca(sizeof(Var)); // prepare variable aParam[aParamCount]->var->mType = VAR_NORMAL; aParam[aParamCount]->var->mAttrib = 0; aParam[aParamCount]->var->mByteCapacity = 0; aParam[aParamCount]->var->mHowAllocated = ALLOC_MALLOC; AssignVariant(*aParam[aParamCount]->var, *variants[aParamCount],false); } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); // free all variables in case memory was allocated for (;aParamCount >= 0;aParamCount--) aParam[aParamCount]->var->Free(); TokenToVariant(aResultToken, variant_to_return_dll); return variant_to_return_dll; } else // UDF { for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) AssignVariant(*aFunc->mParam[aParamCount].var, *variants[aParamCount],false); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; }
tinku99/ahkdll
f9abcfd27eed821d1f19446e1cd9a714d6dc1013
Fixed ahkPostFunction and added A_CoordModeToolTip|Mouse|Menu...
diff --git a/source/exports.cpp b/source/exports.cpp index a8784d7..f7a156d 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,750 +1,750 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(int timeout){return ahkTerminate(timeout);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; - for (int i=0;i < aParamsCount;i++) + for (int i=0;i < 10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) - aParamsCount = i + 1; + aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); return 0; } else { FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; - for (int i = 0;i < 10;i++) + for (int i = 0;i < aParamsCount;i++) { - aFuncAndToken.param[aParamCount] = (LPTSTR)realloc(aFuncAndToken.param[aParamCount],_tcslen(*params[aParamCount])*sizeof(WCHAR)); - _tcscpy(aFuncAndToken.param[aParamCount],*params[aParamCount]); + aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],_tcslen(*params[i])*sizeof(WCHAR)); + _tcscpy(aFuncAndToken.param[i],*params[i]); } //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mStaticVar, func.mStaticVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); g_script.PreprocessLocalVars(func, func.mStaticLazyVar, func.mStaticLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i<10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) - aParamsCount = i + 1; + aParamsCount++; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); switch (aResultToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aResultToken.var->Contents())) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.var->Contents())*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aResultToken.marker)) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.marker)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aResultToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); } return result_to_return_dll; } else // UDF { //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mParamCount = aParamsCount; for (int i = 0;i < aParamsCount;i++) { - aFuncAndToken.param[aParamCount] = (LPTSTR)realloc(aFuncAndToken.param[aParamCount],_tcslen(*params[aParamCount])*sizeof(WCHAR)); - _tcscpy(aFuncAndToken.param[aParamCount],*params[aParamCount]); + aFuncAndToken.param[i] = (LPTSTR)realloc(aFuncAndToken.param[i],_tcslen(*params[i])*sizeof(WCHAR)); + _tcscpy(aFuncAndToken.param[i],*params[i]); } aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); for (int aParamCount = 0;func.mParamCount > aParamCount && aFuncAndToken->mParamCount > aParamCount;aParamCount++) func.mParam[aParamCount].var->AssignString(aFuncAndToken->param[aParamCount]); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { VARIANT *variants[10]; int aParamCount = 0; variants[0]=&param1;variants[1]=&param2;variants[2]=&param3;variants[3]=&param4;variants[4]=&param5; variants[5]=&param6;variants[6]=&param7;variants[7]=&param8;variants[8]=&param9;variants[9]=&param10; if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_VAR; aParam[aParamCount]->var = (Var*)alloca(sizeof(Var)); // prepare variable aParam[aParamCount]->var->mType = VAR_NORMAL; aParam[aParamCount]->var->mAttrib = 0; aParam[aParamCount]->var->mByteCapacity = 0; aParam[aParamCount]->var->mHowAllocated = ALLOC_MALLOC; AssignVariant(*aParam[aParamCount]->var, *variants[aParamCount],false); } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); // free all variables in case memory was allocated for (;aParamCount >= 0;aParamCount--) aParam[aParamCount]->var->Free(); TokenToVariant(aResultToken, variant_to_return_dll); return variant_to_return_dll; } else // UDF { for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) AssignVariant(*aFunc->mParam[aParamCount].var, *variants[aParamCount],false); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/script.cpp b/source/script.cpp index 228d1b5..20d900d 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -10827,1024 +10827,1025 @@ Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, i result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } } else // !search_static && !search_local { var = mVar; right = mVarCount - 1; // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } if (!search_local) { var = mLazyVar; right = mLazyVarCount - 1; } if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below). { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } } // Since above didn't return, no match was found and "left" always contains the position where aVarName // should be inserted to keep the list sorted. The item is always inserted into the lazy list unless // there is no lazy list. // Set the output parameter, if present: if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below. *apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order. if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match. *apIsLocal = search_local; // Since no match was found, if this is a local fall back to searching the list of globals at runtime // if the caller didn't insist on a particular type: if (search_local && aScope == FINDVAR_DEFAULT) { // In this case, callers want to fall back to globals when a local wasn't found. However, // they want the insertion (if our caller will be doing one) to insert according to the // current assume-mode. Therefore, if the mode is assume-global, pass the apIsLocal // and apInsertPos variables to FindVar() so that it will update them to be global. if (g.CurrentFunc->mDefaultVarType == VAR_DECLARE_GLOBAL) return FindVar(aVarName, aVarNameLength, apInsertPos, FINDVAR_GLOBAL, apIsLocal); // v1: Each *dynamic* variable reference may resolve to a global if one exists. if (mIsReadyToExecute) return FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL); // Otherwise, caller only wants globals which are declared in *this* function: for (int i = 0; i < g.CurrentFunc->mGlobalVarCount; ++i) if (!_tcsicmp(var_name, g.CurrentFunc->mGlobalVar[i]->mName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return g.CurrentFunc->mGlobalVar[i]; // As a last resort, check for a super-global: Var *gvar = FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL, NULL); if (gvar && gvar->IsSuperGlobal()) return gvar; } // Otherwise, since above didn't return: return NULL; // No match. } Var *Script::AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope) // Returns the address of the new variable or NULL on failure. // Caller must ensure that g->CurrentFunc!=NULL whenever aIsLocal!=0. // Caller must ensure that aVarName isn't NULL and that this isn't a duplicate variable name. // In addition, it has provided aInsertPos, which is the insertion point so that the list stays sorted. // Finally, aIsLocal has been provided to indicate which list, global or local, should receive this // new variable, as well as the type of local variable. (See the declaration of VAR_LOCAL etc.) { if (!*aVarName) // Should never happen, so just silently indicate failure. return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); if (aVarNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Variable name too long."), aVarName); return NULL; } // Make a temporary copy that includes only the first aVarNameLength characters from aVarName: TCHAR var_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(var_name, aVarName, aVarNameLength + 1); // See explanation above. +1 to convert length to size. if (!Var::ValidateName(var_name)) // Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit). return NULL; bool aIsLocal = (aScope & VAR_LOCAL); // Not necessary or desirable to add built-in variables to a function's list of locals. Always keep // built-in vars in the global list for efficiency and to keep them out of ListVars. Note that another // section at loadtime displays an error for any attempt to explicitly declare built-in variables as // either global or local. void *var_type = GetVarType(var_name); if (aIsLocal && (var_type != (void *)VAR_NORMAL || !_tcsicmp(var_name, _T("ErrorLevel")))) // Attempt to create built-in variable as local. { if ( !(aScope & VAR_LOCAL_FUNCPARAM) ) // It's not a UDF's parameter, so fall back to the global built-in variable of this name rather than displaying an error. return FindOrAddVar(var_name, aVarNameLength, FINDVAR_GLOBAL); // Force find-or-create of global. else // (aIsLocal & VAR_LOCAL_FUNCPARAM), which means "this is a local variable and a function's parameter". { ScriptError(_T("Illegal parameter name."), aVarName); // Short message since so rare. return NULL; } } // Allocate some dynamic memory to pass to the constructor: LPTSTR new_name = SimpleHeap::Malloc(var_name, aVarNameLength); if (!new_name) // It already displayed the error for us. return NULL; // Below specifically tests for VAR_LOCAL and excludes other non-zero values/flags: // VAR_LOCAL_FUNCPARAM should not be made static. // VAR_LOCAL_STATIC is already static. // VAR_DECLARED indicates mDefaultVarType is irrelevant. if (aScope == VAR_LOCAL && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_STATIC) // v1.0.48: Lexikos: Current function is assume-static, so set static attribute. aScope |= VAR_LOCAL_STATIC; bool aIsStatic = aIsLocal ? (aScope & VAR_LOCAL_STATIC) : false; Var *the_new_var = new Var(new_name, var_type, aScope); if (the_new_var == NULL) { ScriptError(ERR_OUTOFMEM); return NULL; } // If there's a lazy var list, aInsertPos provided by the caller is for it, so this new variable // always gets inserted into that list because there's always room for one more (because the // previously added variable would have purged it if it had reached capacity). Var **lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar); int &lazy_var_count = aIsStatic ? g->CurrentFunc->mStaticLazyVarCount : (aIsLocal ? g->CurrentFunc->mLazyVarCount : mLazyVarCount); // Used further below too. if (lazy_var) { if (aInsertPos != lazy_var_count) // Need to make room at the indicated position for this variable. memmove(lazy_var + aInsertPos + 1, lazy_var + aInsertPos, (lazy_var_count - aInsertPos) * sizeof(Var *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. lazy_var[aInsertPos] = the_new_var; ++lazy_var_count; // In a testing creating between 200,000 and 400,000 variables, using a size of 1000 vs. 500 improves // the speed by 17%, but when you subtract out the binary search time (leaving only the insert time), // the increase is more like 34%. But there is a diminishing return after that: Going to 2000 only // gains 20%, and to 4000 only gains an addition 10%. Therefore, to conserve memory in functions that // have so many variables that the lazy list is used, a good trade-off seems to be 2000 (8 KB of memory) // per function that needs it. #define MAX_LAZY_VARS 2000 // Don't make this larger than 90000 without altering the incremental increase of alloc_count further below. if (lazy_var_count < MAX_LAZY_VARS) // The lazy list hasn't yet reached capacity, so no need to merge it into the main list. return the_new_var; } // Since above didn't return, either there is no lazy list or the lazy list is full and needs to be // merged into the main list. // Create references to whichever variable list (local or global) is being acted upon. These // references simplify the code: Var **&var = aIsStatic ? g->CurrentFunc->mStaticVar : (aIsLocal ? g->CurrentFunc->mVar : mVar); // This needs to be a ref. too in case it needs to be realloc'd. int &var_count = aIsStatic ? g->CurrentFunc->mStaticVarCount : (aIsLocal ? g->CurrentFunc->mVarCount : mVarCount); int &var_count_max = aIsStatic ? g->CurrentFunc->mStaticVarCountMax : (aIsLocal ? g->CurrentFunc->mVarCountMax : mVarCountMax); int alloc_count; // Since the above would have returned if the lazy list is present but not yet full, if the left side // of the OR below is false, it also means that lazy_var is NULL. Thus lazy_var==NULL is implicit for the // right side of the OR: if ((lazy_var && var_count + MAX_LAZY_VARS > var_count_max) || var_count == var_count_max) { // Increase by orders of magnitude each time because realloc() is probably an expensive operation // in terms of hurting performance. So here, a little bit of memory is sacrificed to improve // the expected level of performance for scripts that use hundreds of thousands of variables. if (!var_count_max) alloc_count = aIsLocal ? 100 : 1000; // 100 conserves memory since every function needs such a block, and most functions have much fewer than 100 local variables. else if (var_count_max < 1000) alloc_count = 1000; else if (var_count_max < 9999) // Making this 9999 vs. 10000 allows an exact/whole number of lazy_var blocks to fit into main indices between 10000 and 99999 alloc_count = 9999; else if (var_count_max < 100000) { alloc_count = 100000; // This is also the threshold beyond which the lazy list is used to accelerate performance. // Create the permanent lazy list: Var **&lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar); if ( !(lazy_var = (Var **)malloc(MAX_LAZY_VARS * sizeof(Var *))) ) { ScriptError(ERR_OUTOFMEM); return NULL; } } else if (var_count_max < 1000000) alloc_count = 1000000; else alloc_count = var_count_max + 1000000; // i.e. continue to increase by 4MB (1M*4) each time. Var **temp = (Var **)realloc(var, alloc_count * sizeof(Var *)); // If passed NULL, realloc() will do a malloc(). if (!temp) { ScriptError(ERR_OUTOFMEM); return NULL; } var = temp; var_count_max = alloc_count; } if (!lazy_var) { if (aInsertPos != var_count) // Need to make room at the indicated position for this variable. memmove(var + aInsertPos + 1, var + aInsertPos, (var_count - aInsertPos) * sizeof(Var *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. var[aInsertPos] = the_new_var; ++var_count; return the_new_var; } //else the variable was already inserted into the lazy list, so the above is not done. // Since above didn't return, the lazy list is not only present, but full because otherwise it // would have returned higher above. // Since the lazy list is now at its max capacity, merge it into the main list (if the // main list was at capacity, this section relies upon the fact that the above already // increased its capacity by an amount far larger than the number of items contained // in the lazy list). // LAZY LIST: Although it's not nearly as good as hashing (which might be implemented in the future, // though it would be no small undertaking since it affects so many design aspects, both load-time // and runtime for scripts), this method of accelerating insertions into a binary search array is // enormously beneficial because it improves the scalability of binary-search by two orders // of magnitude (from about 100,000 variables to at least 5M). Credit for the idea goes to Lazlo. // DETAILS: // The fact that this merge operation is so much faster than total work required // to insert each one into the main list is the whole reason for having the lazy // list. In other words, the large memmove() that would otherwise be required // to insert each new variable into the main list is completely avoided. Large memmove()s // become dramatically more costly than small ones because apparently they can't fit into // the CPU cache, so the operation would take hundreds or even thousands of times longer // depending on the speed difference between main memory and CPU cache. But above and // beyond the CPU cache issue, the lazy sorting method results in vastly less memory // being moved than would have been required without it, so even if the CPU doesn't have // a cache, the lazy list method vastly increases performance for scripts that have more // than 100,000 variables, allowing at least 5 million variables to be created without a // dramatic reduction in performance. LPTSTR target_name; Var **insert_pos, **insert_pos_prev; int i, left, right, mid; // Append any items from the lazy list to the main list that are alphabetically greater than // the last item in the main list. Above has already ensured that the main list is large enough // to accept all items in the lazy list. for (i = lazy_var_count - 1, target_name = var[var_count - 1]->mName ; i > -1 && _tcsicmp(target_name, lazy_var[i]->mName) < 0 ; --i); // Above is a self-contained loop. // Now do a separate loop to append (in the *correct* order) anything found above. for (int j = i + 1; j < lazy_var_count; ++j) // Might have zero iterations. var[var_count++] = lazy_var[j]; lazy_var_count = i + 1; // The number of items that remain after moving out those that qualified. // This will have zero iterations if the above already moved them all: for (insert_pos = var + var_count, i = lazy_var_count - 1; i > -1; --i) { // Modified binary search that relies on the fact that caller has ensured a match will never // be found in the main list for each item in the lazy list: for (target_name = lazy_var[i]->mName, left = 0, right = (int)(insert_pos - var - 1); left <= right;) { mid = (left + right) / 2; if (_tcsicmp(target_name, var[mid]->mName) > 0) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. left = mid + 1; else // it must be < 0 because caller has ensured it can't be equal (i.e. that there will be no match) right = mid - 1; } // Now "left" contains the insertion point and is known to be less than var_count due to a previous // set of loops above. Make a gap there large enough to hold all items because that allows a // smaller total amount of memory to be moved by shifting the gap to the left in the main list, // gradually filling it as we go: insert_pos_prev = insert_pos; // "prev" is the now the position of the beginning of the gap, but the gap is about to be shifted left by moving memory right. insert_pos = var + left; // This is where it *would* be inserted if we weren't doing the accelerated merge. memmove(insert_pos + i + 1, insert_pos, (insert_pos_prev - insert_pos) * sizeof(Var *)); var[left + i] = lazy_var[i]; // Now insert this item at the far right side of the gap just created. } var_count += lazy_var_count; lazy_var_count = 0; // Indicate that the lazy var list is now empty. return the_new_var; } void *Script::GetVarType(LPTSTR aVarName) { // Convert to lowercase to help performance a little (it typically only helps loadtime performance because // this function is rarely called during script-runtime). TCHAR lowercase[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(lowercase, aVarName, _countof(lowercase)); // Caller should have ensured it fits, but call strlcpy() for maintainability. CharLower(lowercase); // Above: CharLower() is smaller in code size than strlwr(), but CharLower uses the OS locale and strlwr uses // the setlocal() locale (which is always the same if setlocal() is never called). However, locale // differences shouldn't affect the cases checked below; some evidence of this is at MSDN: // "CharLower always maps uppercase I to lowercase I, even when the current language is Turkish or Azeri." if (lowercase[0] != 'a' || lowercase[1] != '_') // This check helps average-case performance. { if ( !_tcscmp(lowercase, _T("true")) || !_tcscmp(lowercase, _T("false"))) return BIV_True_False; if (!_tcscmp(lowercase, _T("clipboard"))) return (void *)VAR_CLIPBOARD; if (!_tcscmp(lowercase, _T("clipboardall"))) return (void *)VAR_CLIPBOARDALL; if (!_tcscmp(lowercase, _T("comspec"))) return BIV_ComSpec; // Lacks an "A_" prefix for backward compatibility with pre-NoEnv scripts and also it's easier to type & remember. if (!_tcscmp(lowercase, _T("programfiles"))) return BIV_SpecialFolderPath; // v1.0.43.08: Added to ease the transition to #NoEnv. // Otherwise: return (void *)VAR_NORMAL; } // Otherwise, lowercase begins with "a_", so it's probably one of the built-in variables. LPTSTR lower = lowercase + 2; // Keeping the most common ones near the top helps performance a little. if (!_tcscmp(lower, _T("index"))) return BIV_LoopIndex; // A short name since it's typed so often. if ( !_tcscmp(lower, _T("mmmm")) // Long name of month. || !_tcscmp(lower, _T("mmm")) // 3-char abbrev. month name. || !_tcscmp(lower, _T("dddd")) // Name of weekday, e.g. Sunday || !_tcscmp(lower, _T("ddd")) ) // Abbrev., e.g. Sun return BIV_MMM_DDD; if ( !_tcscmp(lower, _T("yyyy")) || !_tcscmp(lower, _T("year")) // Same as above. || !_tcscmp(lower, _T("mm")) // 01 thru 12 || !_tcscmp(lower, _T("mon")) // Same || !_tcscmp(lower, _T("dd")) // 01 thru 31 || !_tcscmp(lower, _T("mday")) // Same || !_tcscmp(lower, _T("wday")) || !_tcscmp(lower, _T("yday")) || !_tcscmp(lower, _T("yweek")) || !_tcscmp(lower, _T("hour")) || !_tcscmp(lower, _T("min")) || !_tcscmp(lower, _T("sec")) || !_tcscmp(lower, _T("msec")) ) return BIV_DateTime; if (!_tcscmp(lower, _T("tickcount"))) return BIV_TickCount; if ( !_tcscmp(lower, _T("now")) || !_tcscmp(lower, _T("nowutc"))) return BIV_Now; if (!_tcscmp(lower, _T("workingdir"))) return BIV_WorkingDir; if (!_tcscmp(lower, _T("scriptname"))) return BIV_ScriptName; if (!_tcscmp(lower, _T("scriptdir"))) return BIV_ScriptDir; if (!_tcscmp(lower, _T("scriptfullpath"))) return BIV_ScriptFullPath; if (!_tcscmp(lower, _T("scripthwnd"))) return BIV_ScriptHwnd; if (!_tcscmp(lower, _T("linenumber"))) return BIV_LineNumber; if (!_tcscmp(lower, _T("linefile"))) return BIV_LineFile; //#ifdef AUTOHOTKEYSC if (!_tcscmp(lower, _T("iscompiled"))) return BIV_IsCompiled; //#endif if (!_tcscmp(lower, _T("isunicode"))) return BIV_IsUnicode; if (!_tcscmp(lower, _T("ptrsize"))) return BIV_PtrSize; if ( !_tcscmp(lower, _T("batchlines")) || !_tcscmp(lower, _T("numbatchlines"))) return BIV_BatchLines; if (!_tcscmp(lower, _T("titlematchmode"))) return BIV_TitleMatchMode; if (!_tcscmp(lower, _T("titlematchmodespeed"))) return BIV_TitleMatchModeSpeed; if (!_tcscmp(lower, _T("detecthiddenwindows"))) return BIV_DetectHiddenWindows; if (!_tcscmp(lower, _T("detecthiddentext"))) return BIV_DetectHiddenText; if (!_tcscmp(lower, _T("autotrim"))) return BIV_AutoTrim; if (!_tcscmp(lower, _T("stringcasesense"))) return BIV_StringCaseSense; if (!_tcscmp(lower, _T("formatinteger"))) return BIV_FormatInteger; if (!_tcscmp(lower, _T("formatfloat"))) return BIV_FormatFloat; if (!_tcscmp(lower, _T("keydelay"))) return BIV_KeyDelay; if (!_tcscmp(lower, _T("windelay"))) return BIV_WinDelay; if (!_tcscmp(lower, _T("controldelay"))) return BIV_ControlDelay; if (!_tcscmp(lower, _T("mousedelay"))) return BIV_MouseDelay; if (!_tcscmp(lower, _T("defaultmousespeed"))) return BIV_DefaultMouseSpeed; if (!_tcscmp(lower, _T("ispaused"))) return BIV_IsPaused; if (!_tcscmp(lower, _T("iscritical"))) return BIV_IsCritical; if (!_tcscmp(lower, _T("fileencoding"))) return BIV_FileEncoding; if (!_tcscmp(lower, _T("regview"))) return BIV_RegView; #ifndef MINIDLL if (!_tcscmp(lower, _T("issuspended"))) return BIV_IsSuspended; if (!_tcscmp(lower, _T("iconhidden"))) return BIV_IconHidden; if (!_tcscmp(lower, _T("icontip"))) return BIV_IconTip; if (!_tcscmp(lower, _T("iconfile"))) return BIV_IconFile; if (!_tcscmp(lower, _T("iconnumber"))) return BIV_IconNumber; #endif if (!_tcscmp(lower, _T("exitreason"))) return BIV_ExitReason; if (!_tcscmp(lower, _T("ostype"))) return BIV_OSType; if (!_tcscmp(lower, _T("osversion"))) return BIV_OSVersion; if (!_tcscmp(lower, _T("is64bitos"))) return BIV_Is64bitOS; if (!_tcscmp(lower, _T("language"))) return BIV_Language; if ( !_tcscmp(lower, _T("computername")) || !_tcscmp(lower, _T("username"))) return BIV_UserName_ComputerName; if (!_tcscmp(lower, _T("windir"))) return BIV_WinDir; if (!_tcscmp(lower, _T("temp"))) return BIV_Temp; // Debatably should be A_TempDir, but brevity seemed more popular with users, perhaps for heavy uses of the temp folder. if (!_tcscmp(lower, _T("mydocuments"))) return BIV_MyDocuments; if ( !_tcscmp(lower, _T("programfiles")) || !_tcscmp(lower, _T("appdata")) || !_tcscmp(lower, _T("appdatacommon")) || !_tcscmp(lower, _T("desktop")) || !_tcscmp(lower, _T("desktopcommon")) || !_tcscmp(lower, _T("startmenu")) || !_tcscmp(lower, _T("startmenucommon")) || !_tcscmp(lower, _T("programs")) || !_tcscmp(lower, _T("programscommon")) || !_tcscmp(lower, _T("startup")) || !_tcscmp(lower, _T("startupcommon"))) return BIV_SpecialFolderPath; if (!_tcscmp(lower, _T("isadmin"))) return BIV_IsAdmin; if (!_tcscmp(lower, _T("cursor"))) return BIV_Cursor; if ( !_tcscmp(lower, _T("caretx")) || !_tcscmp(lower, _T("carety"))) return BIV_Caret; if ( !_tcscmp(lower, _T("screenwidth")) || !_tcscmp(lower, _T("screenheight"))) return BIV_ScreenWidth_Height; if (!_tcsncmp(lower, _T("ipaddress"), 9)) { lower += 9; return (*lower >= '1' && *lower <= '4' && !lower[1]) // Make sure has only one more character rather than none or several (e.g. A_IPAddress1abc should not be match). ? BIV_IPAddress : (void *)VAR_NORMAL; // Otherwise it can't be a match for any built-in variable. } if (!_tcsncmp(lower, _T("loop"), 4)) { lower += 4; if (!_tcscmp(lower, _T("readline"))) return BIV_LoopReadLine; if (!_tcscmp(lower, _T("field"))) return BIV_LoopField; if (!_tcsncmp(lower, _T("file"), 4)) { lower += 4; if (!_tcscmp(lower, _T("name"))) return BIV_LoopFileName; if (!_tcscmp(lower, _T("shortname"))) return BIV_LoopFileShortName; if (!_tcscmp(lower, _T("ext"))) return BIV_LoopFileExt; if (!_tcscmp(lower, _T("dir"))) return BIV_LoopFileDir; if (!_tcscmp(lower, _T("fullpath"))) return BIV_LoopFileFullPath; if (!_tcscmp(lower, _T("longpath"))) return BIV_LoopFileLongPath; if (!_tcscmp(lower, _T("shortpath"))) return BIV_LoopFileShortPath; if (!_tcscmp(lower, _T("attrib"))) return BIV_LoopFileAttrib; if ( !_tcscmp(lower, _T("timemodified")) || !_tcscmp(lower, _T("timecreated")) || !_tcscmp(lower, _T("timeaccessed"))) return BIV_LoopFileTime; if ( !_tcscmp(lower, _T("size")) || !_tcscmp(lower, _T("sizekb")) || !_tcscmp(lower, _T("sizemb"))) return BIV_LoopFileSize; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } if (!_tcsncmp(lower, _T("reg"), 3)) { lower += 3; if (!_tcscmp(lower, _T("type"))) return BIV_LoopRegType; if (!_tcscmp(lower, _T("key"))) return BIV_LoopRegKey; if (!_tcscmp(lower, _T("subkey"))) return BIV_LoopRegSubKey; if (!_tcscmp(lower, _T("name"))) return BIV_LoopRegName; if (!_tcscmp(lower, _T("timemodified"))) return BIV_LoopRegTimeModified; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } } if (!_tcscmp(lower, _T("thisfunc"))) return BIV_ThisFunc; if (!_tcscmp(lower, _T("thislabel"))) return BIV_ThisLabel; #ifndef MINIDLL if (!_tcscmp(lower, _T("thismenuitem"))) return BIV_ThisMenuItem; if (!_tcscmp(lower, _T("thismenuitempos"))) return BIV_ThisMenuItemPos; if (!_tcscmp(lower, _T("thismenu"))) return BIV_ThisMenu; if (!_tcscmp(lower, _T("thishotkey"))) return BIV_ThisHotkey; if (!_tcscmp(lower, _T("priorhotkey"))) return BIV_PriorHotkey; if (!_tcscmp(lower, _T("timesincethishotkey"))) return BIV_TimeSinceThisHotkey; if (!_tcscmp(lower, _T("timesincepriorhotkey"))) return BIV_TimeSincePriorHotkey; if (!_tcscmp(lower, _T("endchar"))) return BIV_EndChar; #endif if (!_tcscmp(lower, _T("lasterror"))) return BIV_LastError; if (!_tcscmp(lower, _T("globalstruct"))) return BIV_GlobalStruct; if (!_tcscmp(lower, _T("scriptstruct"))) return BIV_ScriptStruct; if (!_tcscmp(lower, _T("modulehandle"))) return BIV_ModuleHandle; if (!_tcscmp(lower, _T("isdll"))) return BIV_IsDll; + if (!_tcsncmp(lower, _T("coordmode"), 9)) return BIV_CoordMode; if (!_tcscmp(lower, _T("eventinfo"))) return BIV_EventInfo; // It's called "EventInfo" vs. "GuiEventInfo" because it applies to non-Gui events such as OnClipboardChange. #ifndef MINIDLL if (!_tcscmp(lower, _T("guicontrol"))) return BIV_GuiControl; if ( !_tcscmp(lower, _T("guicontrolevent")) // v1.0.36: A_GuiEvent was added as a synonym for A_GuiControlEvent because it seems unlikely that A_GuiEvent will ever be needed for anything: || !_tcscmp(lower, _T("guievent"))) return BIV_GuiEvent; if ( !_tcscmp(lower, _T("gui")) || !_tcscmp(lower, _T("guiwidth")) || !_tcscmp(lower, _T("guiheight")) || !_tcscmp(lower, _T("guix")) // Naming: Brevity seems more a benefit than would A_GuiEventX's improved clarity. || !_tcscmp(lower, _T("guiy"))) return BIV_Gui; // These can be overloaded if a GuiMove label or similar is ever needed. if (!_tcscmp(lower, _T("priorkey"))) return BIV_PriorKey; #endif if (!_tcscmp(lower, _T("timeidle"))) return BIV_TimeIdle; if (!_tcscmp(lower, _T("timeidlephysical"))) return BIV_TimeIdlePhysical; if ( !_tcscmp(lower, _T("space")) || !_tcscmp(lower, _T("tab"))) return BIV_Space_Tab; if (!_tcscmp(lower, _T("ahkversion"))) return BIV_AhkVersion; if (!_tcscmp(lower, _T("ahkpath"))) return BIV_AhkPath; if (!_tcscmp(lower, _T("dllpath"))) return BIV_DllPath; // Since above didn't return: return (void *)VAR_NORMAL; } WinGroup *Script::FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound) // Caller must ensure that aGroupName isn't NULL. But if it's the empty string, NULL is returned. // Returns the Group whose name matches aGroupName. If it doesn't exist, it is created if aCreateIfNotFound==true. // Thread-safety: This function is thread-safe (except when called with aCreateIfNotFound==true) even when // the main thread happens to be calling AddGroup() and changing the linked list while it's being traversed here // by the hook thread. However, any subsequent changes to this function or AddGroup() must be carefully reviewed. { if (!*aGroupName) { if (aCreateIfNotFound) // An error message must be shown in this case since or caller is about to // exit the current script thread (and we don't want it to happen silently). ScriptError(_T("Blank group name.")); return NULL; } for (WinGroup *group = mFirstGroup; group != NULL; group = group->mNextGroup) if (!_tcsicmp(group->mName, aGroupName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return group; // Match found. // Otherwise, no match found, so create a new group. if (!aCreateIfNotFound || AddGroup(aGroupName) != OK) return NULL; return mLastGroup; } ResultType Script::AddGroup(LPTSTR aGroupName) // Returns OK or FAIL. // The caller must already have verified that this isn't a duplicate group. // This function is not thread-safe because it adds an entry to the quasi-global list of window groups. // In addition, if this function is being called by one thread while another thread is calling FindGroup(), // the thread-safety notes in FindGroup() apply. { size_t aGroupName_length = _tcslen(aGroupName); if (aGroupName_length > MAX_VAR_NAME_LENGTH) return ScriptError(_T("Group name too long."), aGroupName); if (!Var::ValidateName(aGroupName, DISPLAY_NO_ERROR)) // Seems best to use same validation as var names. return ScriptError(_T("Illegal group name."), aGroupName); LPTSTR new_name = SimpleHeap::Malloc(aGroupName, aGroupName_length); if (!new_name) return FAIL; // It already displayed the error for us. // The precise method by which the follows steps are done should be thread-safe even if // some other thread calls FindGroup() in the middle of the operation. But any changes // must be carefully reviewed: WinGroup *the_new_group = new WinGroup(new_name); if (the_new_group == NULL) return ScriptError(ERR_OUTOFMEM); if (mFirstGroup == NULL) mFirstGroup = the_new_group; else mLastGroup->mNextGroup = the_new_group; // This must be done after the above: mLastGroup = the_new_group; return OK; } Line *Script::PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd, Line *aParentLine) // aFindBlockEnd should be true, only when this function is called // by itself. The end of this function relies upon this definition. // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). { // Not thread-safe, so this can only parse one script at a time. // Not a problem for the foreseeable future: static int nest_level; // Level zero is the outermost one: outside all blocks. static bool abort; if (!aParentLine) { // We were called from outside, not recursively, so init these. This is // very important if this function is ever to be called from outside // more than once, even though it isn't currently: nest_level = 0; abort = false; } int i; DerefType *deref; // Don't check aStartingLine here at top: only do it at the bottom // for its differing return values. for (Line *line = aStartingLine; line;) { // Check if any of each arg's derefs are function calls. If so, do some validation and // preprocessing to set things up for better runtime performance: for (i = 0; i < line->mArgc; ++i) // For each arg. { ArgStruct &this_arg = line->mArg[i]; // For performance and convenience. // Exclude the derefs of output and input vars from consideration, since they can't // be function calls: if (!this_arg.is_expression) // For now, only expressions are capable of calling functions. If ever change this, might want to add a check here for this_arg.type != ARG_TYPE_NORMAL (for performance). continue; if (this_arg.deref) // No function-calls are present because the expression contains neither variables nor function calls. { for (deref = this_arg.deref; deref->marker; ++deref) // For each deref. { if (!deref->is_function) continue; if ( !(deref->func = FindFunc(deref->marker, deref->length)) ) { #ifndef AUTOHOTKEYSC bool error_was_shown, file_was_found; if ( !(deref->func = FindFuncInLibrary(deref->marker, deref->length, error_was_shown, file_was_found, true)) ) { abort = true; // So that the caller doesn't also report an error. // When above already displayed the proximate cause of the error, it's usually // undesirable to show the cascade effects of that error in a second dialog: return error_was_shown ? NULL : line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); } #else abort = true; return line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); #endif } // L31: Parameter counting and validation was previously done in this section, // but is now handled by ExpressionToPostfix. } // for each deref of this arg } // if (this_arg.deref) if (!line->ExpressionToPostfix(this_arg)) // At this stage, this_arg.is_expression is known to be true. Doing this here, after the script has been loaded, might improve the compactness/adjacent-ness of the compiled expressions in memory, which might improve performance due to CPU caching. { abort = true; // So that the caller doesn't also report an error. return NULL; // The function above already displayed the error msg. } } // for each arg of this line // All lines in our recursion layer are assigned to the block that the caller specified: if (line->mParentLine == NULL) // i.e. don't do it if it's already "owned" by an IF or ELSE. line->mParentLine = aParentLine; // Can be NULL. if (ACT_IS_IF_OR_ELSE_OR_LOOP(line->mActionType) || line->mActionType == ACT_REPEAT) { // In this case, the loader should have already ensured that line->mNextLine is not NULL. if (line->mNextLine->mActionType == ACT_BLOCK_BEGIN && line->mNextLine->mAttribute == ATTR_TRUE) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Improper line below this.")); // Short message since so rare. A function must not be defined directly below an IF/ELSE/LOOP because runtime evaluation won't handle it properly. } if (line->mActionType == ACT_FOR) { ASSERT(line->mArgc == 3); // Now that this FOR's expression has been pre-parsed, exclude it from mArgc so that ExpandArgs() // won't evaluate it -- PerformLoopFor() needs to call ExpandExpression() directly in order to // receive the object reference which is the result of the expression. line->mArgc--; } // Make the line immediately following each ELSE, IF or LOOP be enclosed by that stmt. // This is done to make it illegal for a Goto or Gosub to jump into a deeper layer, // such as in this example: // #y:: // ifwinexist, pad // { // goto, label1 // ifwinexist, pad // label1: // ; With or without the enclosing block, the goto would still go to an illegal place // ; in the below, resulting in an "unexpected else" error: // { // msgbox, ifaction // } ; not necessary to make this line enclosed by the if because labels can't point to it? // else // msgbox, elseaction // } // return line->mNextLine->mParentLine = line; // Go onto the IF's or ELSE's action in case it too is an IF, rather than skipping over it: line = line->mNextLine; continue; } switch (line->mActionType) { case ACT_BLOCK_BEGIN: // Some insane limit too large to ever likely be exceeded, yet small enough not // to be a risk of stack overflow when recursing in ExecUntil(). Mostly, this is // here to reduce the chance of a program crash if a binary file, a corrupted file, // or something unexpected has been loaded as a script when it shouldn't have been. // Update: Increased the limit from 100 to 1000 so that large "else if" ladders // can be constructed. Going much larger than 1000 seems unwise since ExecUntil() // will have to recurse for each nest-level, possibly resulting in stack overflow // if things get too deep: if (nest_level > 1000) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Nesting too deep.")); // Short msg since so rare. } // Since the current convention is to store the line *after* the // BLOCK_END as the BLOCK_BEGIN's related line, that line can // be legitimately NULL if this block's BLOCK_END is the last // line in the script. So it's up to the called function // to report an error if it never finds a BLOCK_END for us. // UPDATE: The design requires that we do it here instead: ++nest_level; if (NULL == (line->mRelatedLine = PreparseBlocks(line->mNextLine, 1, line))) if (abort) // the above call already reported the error. return NULL; else { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(ERR_MISSING_CLOSE_BRACE); } --nest_level; // The convention is to have the BLOCK_BEGIN's related_line // point to the line *after* the BLOCK_END. line->mRelatedLine = line->mRelatedLine->mNextLine; // Might be NULL now. // Otherwise, since any blocks contained inside this one would already // have been handled by the recursion in the above call, continue searching // from the end of this block: line = line->mRelatedLine; // If NULL, the loop-condition will catch it. break; case ACT_BLOCK_END: // Return NULL (failure) if the end was found but we weren't looking for one // (i.e. it's an orphan). Otherwise return the line after the block_end line, // which will become the caller's mRelatedLine. UPDATE: Return the // END_BLOCK line itself so that the caller can differentiate between // a NULL due to end-of-script and a NULL caused by an error: return aFindBlockEnd ? line // Doesn't seem necessary to set abort to true. : line->PreparseError(ERR_MISSING_OPEN_BRACE); default: // Continue line-by-line. line = line->mNextLine; } // switch() } // for each line // End of script has been reached. <line> is now NULL so don't attempt to dereference it. // If we were still looking for an EndBlock to match up with a begin, that's an error. // Don't report the error here because we don't know which begin-block is waiting // for an end (the caller knows and must report the error). UPDATE: Must report // the error here (see comments further above for explanation). UPDATE #2: Changed // it again: Now we let the caller handle it again: if (aFindBlockEnd) //return mLastLine->PreparseError("The script ends while a block is still open (missing })."); return NULL; // If no error, return something non-NULL to indicate success to the top-level caller. // We know we're returning to the top-level caller because aFindBlockEnd is only true // when we're recursed, and in that case the above would have returned. Thus, // we're not recursed upon reaching this line: return mLastLine; } Line *Script::PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode, AttributeType aLoopType) // Zero is the default for aMode, otherwise: // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). // Note: This function should be called with aMode == ONLY_ONE_LINE // only when aStartingLine's ActionType is something recursable such // as IF and BEGIN_BLOCK. Otherwise, it won't return after only one line. { static BOOL sInFunctionBody = FALSE; // Improves loadtime performance by allowing IsOutsideAnyFunctionBody() to be called only when necessary. // Don't check aStartingLine here at top: only do it at the bottom // for it's differing return values. Line *line_temp; AttributeType loop_type = aLoopType; for (Line *line = aStartingLine; line != NULL;) { if ( ACT_IS_IF(line->mActionType) || line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_REPEAT || line->mActionType == ACT_TRY ) { // ActionType is an IF or a LOOP or a TRY. line_temp = line->mNextLine; // line_temp is now this IF's or LOOP's or TRY's action-line. // Update: Below is commented out because it's now impossible (since all scripts end in ACT_EXIT): //if (line_temp == NULL) // This is an orphan IF/LOOP (has no action-line) at the end of the script. // return line->PreparseError(_T("Q")); // Placeholder. Formerly "This if-statement or loop has no action." // Other things rely on this check having been done, such as "if (line->mRelatedLine != NULL)": if (line_temp->mActionType == ACT_ELSE || line_temp->mActionType == ACT_BLOCK_END || line_temp->mActionType == ACT_CATCH) return line->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Lexikos: This section once maintained separate variables for file-pattern, registry, file-reading // and parsing loops. The intention seemed to be to validate certain commands such as FileAppend // differently depending on whether they're contained within a qualifying type of loop (even if some // other type of loop lies in between). However, that validation apparently wasn't implemented, // and implementing it now seems unnecessary. Doing so would also remove a useful capability: // // Loop, Read, %InputFile%, %OutputFile% // { // MyFunc(A_LoopReadLine) // } // MyFunc(line) { // ... do some processing on %line% ... // FileAppend, %line% ; This line could be considered an error, though it works in practice. // } // // Check if the IF's action-line is something we want to recurse. UPDATE: Always // recurse because other line types, such as Goto and Gosub, need to be preparsed // by this function even if they are the single-line actions of an IF or an ELSE. // Recurse this line rather than the next because we want the called function to // recurse again if this line is a ACT_BLOCK_BEGIN or is itself an IF. line_temp = PreparseIfElse(line_temp, ONLY_ONE_LINE, line->mAttribute ? line->mAttribute : loop_type); // If not end-of-script or error, line_temp is now either: // 1) If this if's/loop's action was a BEGIN_BLOCK: The line after the end of the block. // 2) If this if's/loop's action was another IF or LOOP: // a) the line after that if's else's action; or (if it doesn't have one): // b) the line after that if's/loop's action // 3) If this if's/loop's action was some single-line action: the line after that action. // In all of the above cases, line_temp is now the line where we // would expect to find an ELSE for this IF, if it has one. // Now the above has ensured that line_temp is this line's else, if it has one. // Note: line_temp will be NULL if the end of the script has been reached. // UPDATE: That can't happen now because all scripts end in ACT_EXIT: if (line_temp == NULL) // Error or end-of-script was reached. return NULL; // Seems best to keep this check for maintainability because changes to other checks can impact // whether this check will ever be "true": if (line->mRelatedLine != NULL) return line->PreparseError(_T("Q")); // Placeholder since it shouldn't happen. Formerly "This if-statement or LOOP unexpectedly already had an ELSE or end-point." // Set it to the else's action, rather than the else itself, since the else itself // is never needed during execution. UPDATE: No, instead set it to the ELSE itself // (if it has one) since we jump here at runtime when the IF is finished (whether // it's condition was true or false), thus skipping over any nested IF's that // aren't in blocks beneath it. If there's no ELSE, the below value serves as // the jumppoint we go to when the if-statement is finished. Example: // if x // if y // if z // action1 // else // action2 // action3 // x's jumppoint should be action3 so that all the nested if's // under the first one can be skipped after the "if x" line is recursively // evaluated. Because of this behavior, all IFs will have a related line // with the possibly exception of the very last if-statement in the script // (which is possible only if the script doesn't end in a Return or Exit). line->mRelatedLine = line_temp; // Even if <line> is a LOOP and line_temp and else? // Even if aMode == ONLY_ONE_LINE, an IF and its ELSE count as a single // statement (one line) due to its very nature (at least for this purpose), // so always continue on to evaluate the IF's ELSE, if present: if (line_temp->mActionType == ACT_ELSE) { if (line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_TRY || line->mActionType == ACT_REPEAT) { // this can't be our else, so let the caller handle it. if (aMode != ONLY_ONE_LINE) // This ELSE was encountered while sequentially scanning the contents // of a block or at the outermost nesting layer. More thought is required // to verify this is correct. UPDATE: This check is very old and I haven't // found a case that can produce it yet, but until proven otherwise its safer // to assume it's possible. return line_temp->PreparseError(ERR_ELSE_WITH_NO_IF); // Let the caller handle this else, since it can't be ours: return line_temp; } // Now use line vs. line_temp to hold the new values, so that line_temp // stays as a marker to the ELSE line itself: line = line_temp->mNextLine; // Set it to the else's action line. // Update: The following is now impossible because all scripts end in ACT_EXIT. // Thus, it's commented out: //if (line == NULL) // An else with no action. // return line_temp->PreparseError(_T("Q")); // Placeholder since impossible. Formerly "This ELSE has no action." if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this ELSE's jumppoint. This is similar to the jumppoint set for // an ELSEless IF, so see related comments above: line_temp->mRelatedLine = line; } else if (line_temp->mActionType == ACT_UNTIL) { if (line->mActionType != ACT_LOOP && line->mActionType != ACT_FOR) // Doesn't seem useful to allow it with WHILE? { // This is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_UNTIL_WITH_NO_LOOP); return line_temp; } // Continue processing *after* UNTIL. line = line_temp->mNextLine; } else if (line_temp->mActionType == ACT_CATCH) { if (line->mActionType != ACT_TRY) { // Again, this is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_CATCH_WITH_NO_TRY); return line_temp; } line = line_temp->mNextLine; if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this CATCH's jumppoint. line_temp->mRelatedLine = line; } else // line doesn't have an else, so just continue processing from line_temp's position line = line_temp; // Both cases above have ensured that line is now the first line beyond the // scope of the if-statement and that of any ELSE it may have. if (aMode == ONLY_ONE_LINE) // Return the next unprocessed line to the caller. return line; // Otherwise, continue processing at line's new location: continue; } // ActionType is "IF". // Since above didn't continue, do the switch: LPTSTR line_raw_arg1 = LINE_RAW_ARG1; // Resolve only once to help reduce code size. LPTSTR line_raw_arg2 = LINE_RAW_ARG2; // switch (line->mActionType) { case ACT_BLOCK_BEGIN: if (line->mAttribute == ATTR_TRUE) // This is the opening brace of a function definition. sInFunctionBody = TRUE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. line = PreparseIfElse(line->mNextLine, UNTIL_BLOCK_END, aLoopType); // "line" is now either NULL due to an error, or the location of the END_BLOCK itself. if (line == NULL) return NULL; // Error. break; case ACT_BLOCK_END: if (line->mAttribute == ATTR_TRUE) // This is the closing brace of a function definition. sInFunctionBody = FALSE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. if (aMode == ONLY_ONE_LINE) // Syntax error. The caller would never expect this single-line to be an // end-block. UPDATE: I think this is impossible because callers only use // aMode == ONLY_ONE_LINE when aStartingLine's ActionType is already // known to be an IF or a BLOCK_BEGIN: return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (single)." if (UNTIL_BLOCK_END) // Return line rather than line->mNextLine because, if we're at the end of // the script, it's up to the caller to differentiate between that condition // and the condition where NULL is an error indicator. return line; // Otherwise, we found an end-block we weren't looking for. This should be // impossible since the block pre-parsing already balanced all the blocks? return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (multi)." case ACT_BREAK: case ACT_CONTINUE: if (!aLoopType) return line->PreparseError(_T("Break/Continue must be enclosed by a Loop.")); if (line->mArgc) { if (line->ArgHasDeref(1) || line->mArg->is_expression) // It seems unlikely that computing the target loop at runtime would be useful. // For simplicity, rule out things like "break %var%" and "break % func()": return line->PreparseError(ERR_PARAM1_INVALID); //_T("Target label of Break/Continue cannot be dynamic.")); LPTSTR loop_name = line->mArg[0].text; Label *loop_label; Line *loop_line; if (IsPureNumeric(loop_name)) { int n = _ttoi(loop_name); // Find the nth innermost loop which encloses this line: for (loop_line = line->mParentLine; loop_line; loop_line = loop_line->mParentLine) if (loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) // i.e. LOOP, FOR or WHILE. if (--n < 1) break; if (!loop_line || n != 0) return line->PreparseError(ERR_PARAM1_INVALID); } else { // Target is a named loop. if ( !(loop_label = FindLabel(loop_name)) ) return line->PreparseError(ERR_NO_LABEL, loop_name); loop_line = loop_label->mJumpToLine; // Ensure the label points to a Loop, For-loop or While-loop ... if ( !(loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) diff --git a/source/script.h b/source/script.h index 8d1f0a3..7a7d47a 100644 --- a/source/script.h +++ b/source/script.h @@ -2365,745 +2365,746 @@ struct GuiControlOptionsType 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_listview; // Used only for those controls that need control.union_color for something other than 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 color_changed; // To discern when a control has been put back to the default color. [v1.0.26] 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. }; LRESULT CALLBACK GuiWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK TabWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); class GuiType { public: #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 * sFont[mCurrentFontIndex].point_size) // 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 8 #define PROGRESS_DEFAULT_THICKNESS (2 * sFont[mCurrentFontIndex].point_size) LPTSTR mName; HWND mHwnd, 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 the below amount. This offset is // necessary because windows that behave like dialogs automatically return IDOK and IDCANCEL in // response to certain types of standard actions: GuiIndexType mControlCount; GuiIndexType mControlCapacity; // How many controls can fit into the current memory size of mControl. GuiControlType *mControl; // Will become an array of controls when the window is first created. GuiIndexType mDefaultButtonIndex; // Index vs. pointer is needed for some things. ULONG mReferenceCount; // For keeping this structure in memory during execution of the Gui's labels. Label *mLabelForClose, *mLabelForEscape, *mLabelForSize, *mLabelForDropFiles, *mLabelForContextMenu; bool mLabelForCloseIsRunning, mLabelForEscapeIsRunning, mLabelForSizeIsRunning; // DropFiles doesn't need one of these. bool mLabelsHaveBeenSet; DWORD mStyle, mExStyle; // Style of window. 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. TCHAR mDelimiter; // The default field delimiter when adding items to ListBox, DropDownList, ListView, etc. GuiControlType *mCurrentListView, *mCurrentTreeView; // The ListView and TreeView upon which the LV/TV functions operate. int mCurrentFontIndex; COLORREF mCurrentColor; // The default color of text in controls. COLORREF mBackgroundColorWin; // The window's background color itself. COLORREF mBackgroundColorCtl; // Background color for controls. HBRUSH mBackgroundBrushWin; // Brush corresponding to mBackgroundColorWin. HBRUSH mBackgroundBrushCtl; // Brush corresponding to mBackgroundColorCtl. 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. int mMarginX, mMarginY, mPrevX, mPrevY, mPrevWidth, mPrevHeight, mMaxExtentRight, mMaxExtentDown , mSectionX, mSectionY, mMaxExtentRightSection, mMaxExtentDownSection; LONG mMinWidth, mMinHeight, mMaxWidth, mMaxHeight; 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 mGuiShowHasNeverBeenDone, mFirstActivation, mShowIsInProgress, mDestroyWindowHasBeenCalled; bool mControlWidthWasSetByContents; // Whether the most recently added control was auto-width'd to fit its contents. #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). // Keep the default destructor to avoid entering the "Law of the Big Three": If your class requires a // copy constructor, copy assignment operator, or a destructor, then it very likely will require all three. GuiType() // Constructor : mName(NULL), mHwnd(NULL), mStatusBarHwnd(NULL), mControlCount(0), mControlCapacity(0) , mDefaultButtonIndex(-1), mLabelForClose(NULL), mLabelForEscape(NULL), mLabelForSize(NULL) , mLabelForDropFiles(NULL), mLabelForContextMenu(NULL), mReferenceCount(1) , mLabelForCloseIsRunning(false), mLabelForEscapeIsRunning(false), mLabelForSizeIsRunning(false) , mLabelsHaveBeenSet(false) // 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), mOwner(NULL), mDelimiter('|') , mCurrentFontIndex(FindOrCreateFont()) // Must call this in constructor to ensure sFont array is never NULL while a GUI object exists. Omit params to tell it to find or create DEFAULT_GUI_FONT. , mCurrentListView(NULL), mCurrentTreeView(NULL) , mTabControlCount(0), mCurrentTabControlIndex(MAX_TAB_CONTROLS), mCurrentTabIndex(0) , mCurrentColor(CLR_DEFAULT) , mBackgroundColorWin(CLR_DEFAULT), mBackgroundBrushWin(NULL) , mBackgroundColorCtl(CLR_DEFAULT), mBackgroundBrushCtl(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) { // The array of controls is left uninitialized to catch bugs. Each control's attributes should be // fully populated when it is created. //ZeroMemory(mControl, sizeof(mControl)); } static ResultType Destroy(GuiType &gui); static void DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall); // L17: Renamed function and added parameter to also handle the window's small icon. ResultType Create(); void AddRef(); void Release(); void SetLabels(LPTSTR aLabelPrefix); static void UpdateMenuBars(HMENU aMenu); ResultType AddControl(GuiControls aControlType, LPTSTR aOptions, LPTSTR aText); ResultType ParseOptions(LPTSTR aOptions, bool &aSetLastFoundWindow, ToggleValueType &aOwnDialogs, Var *&aHwndVar); void GetNonClientArea(LONG &aWidth, LONG &aHeight); void GetTotalWidthAndHeight(LONG &aWidth, LONG &aHeight); ResultType ControlParseOptions(LPTSTR aOptions, GuiControlOptionsType &aOpt, GuiControlType &aControl , GuiIndexType aControlIndex = -1); // aControlIndex is not needed upon control creation. void ControlInitOptions(GuiControlOptionsType &aOpt, GuiControlType &aControl); void ControlAddContents(GuiControlType &aControl, LPTSTR aContent, int aChoice, GuiControlOptionsType *aOpt = NULL); ResultType Show(LPTSTR aOptions, LPTSTR aTitle); ResultType Clear(); ResultType Cancel(); ResultType Close(); // Due to SC_CLOSE, etc. ResultType Escape(); // Similar to close, except typically called when the user presses ESCAPE. ResultType Submit(bool aHideIt); ResultType ControlGetContents(Var &aOutputVar, GuiControlType &aControl, LPTSTR aMode = _T("")); static VarSizeType ControlGetName(GuiType *aGuiWindow, GuiIndexType aControlIndex, LPTSTR aBuf); static GuiType *FindGui(LPTSTR aName); static GuiType *FindGui(HWND aHwnd); static GuiType *ValidGui(GuiType *&aGuiRef); // Updates aGuiRef if it points to a destroyed Gui. GuiIndexType FindControl(LPTSTR aControlID); GuiControlType *FindControl(HWND aHwnd, bool aRetrieveIndexInstead = false) { 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) // Not found yet; try again with parent. { // Since ComboBoxes (and possibly other future control types) have children, try looking // up aHwnd's parent to see if its a known control of this dialog. Some callers rely on us making // this extra effort: if (aHwnd = GetParent(aHwnd)) // 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. 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) // A match was found. return aRetrieveIndexInstead ? (GuiControlType *)(size_t)index : mControl + index; else // No match, so indicate failure. return aRetrieveIndexInstead ? (GuiControlType *)NO_CONTROL_INDEX : NULL; } int FindGroup(GuiIndexType aControlIndex, GuiIndexType &aGroupStart, GuiIndexType &aGroupEnd); ResultType SetCurrentFont(LPTSTR aOptions, LPTSTR aFontName); static int FindOrCreateFont(LPTSTR aOptions = _T(""), LPTSTR aFontName = _T(""), FontType *aFoundationFont = NULL , COLORREF *aColor = NULL); static int FindFont(FontType &aFont); void Event(GuiIndexType aControlIndex, UINT aNotifyCode, USHORT aGuiEvent = GUI_EVENT_NONE, UINT aEventInfo = 0); static WORD TextToHotkey(LPTSTR aText); static LPTSTR HotkeyToText(WORD aHotkey, LPTSTR aBuf); 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); bool ControlOverrideBkColor(GuiControlType &aControl); 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); POINT GetPositionOfTabClientArea(GuiControlType &aTabControl); ResultType SelectAdjacentTab(GuiControlType &aTabControl, bool aMoveToRight, bool aFocusFirstControl , bool aWrapAround); void ControlGetPosOfFocusedItem(GuiControlType &aControl, POINT &aPoint); static void LV_Sort(GuiControlType &aControl, int aColumnIndex, bool aSortOnlyIfEnabled, TCHAR aForceDirection = '\0'); static DWORD ControlGetListViewMode(HWND aWnd); 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); }; #endif // MINIDLL typedef NTSTATUS (NTAPI *PFN_NT_QUERY_INFORMATION_PROCESS) ( HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength OPTIONAL); typedef int (* ahkx_int_str)(LPTSTR ahkx_str); // ahkx N11 typedef int (* ahkx_int_str_str)(LPTSTR ahkx_str, LPTSTR ahkx_str2); // ahkx N11 class Script { private: #ifndef MINIDLL friend class Hotkey; #endif #ifdef CONFIG_DEBUGGER friend class Debugger; #endif public: Var **mVar, **mLazyVar; // Array of pointers-to-variable, allocated upon first use and later expanded as needed. int mVarCount, mVarCountMax, mLazyVarCount; // Count of items in the above array as well as the maximum capacity. WinGroup *mFirstGroup, *mLastGroup; // The first and last variables in the linked list. int mCurrentFuncOpenBlockCount; // While loading the script, this is how many blocks are currently open in the current function's body. bool mNextLineIsFunctionBody; // Whether the very next line to be added will be the first one of the body. #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. // 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 mNoHotkeyLabels; #ifndef MINIDLL bool mMenuUseErrorLevel; // Whether runtime errors should be displayed by the Menu command, vs. ErrorLevel. #endif #define UPDATE_TIP_FIELD tcslcpy(mNIC.szTip, (mTrayIconTip && *mTrayIconTip) ? mTrayIconTip \ : (mFileName ? mFileName : T_AHK_NAME), _countof(mNIC.szTip)); NOTIFYICONDATA mNIC; // For ease of adding and deleting our tray icon. size_t GetLine(LPTSTR aBuf, int aMaxCharsToRead, int aInContinuationSection, TextStream *ts); ResultType IsDirective(LPTSTR aBuf); ResultType ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID , ActionTypeType aOldActionType = OLD_INVALID, LPTSTR aActionName = NULL , LPTSTR aEndMarker = NULL, LPTSTR aLiteralMap = NULL, size_t aLiteralMapLength = 0); ResultType ParseDerefs(LPTSTR aArgText, LPTSTR aArgMap, DerefType *aDeref, int &aDerefCount); LPTSTR ParseActionType(LPTSTR aBufTarget, LPTSTR aBufSource, bool aDisplayErrors); static ActionTypeType ConvertActionType(LPTSTR aActionTypeString); static ActionTypeType ConvertOldActionType(LPTSTR aActionTypeString); ResultType AddLabel(LPTSTR aLabelName, bool aAllowDupe); ResultType AddLine(ActionTypeType aActionType, LPTSTR aArg[] = NULL, int aArgc = 0, LPTSTR aArgMap[] = NULL); // These aren't in the Line class because I think they're easier to implement // if aStartingLine is allowed to be NULL (for recursive calls). If they // were member functions of class Line, a check for NULL would have to // be done before dereferencing any line's mNextLine, for example: Line *PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd = false, Line *aParentLine = NULL); Line *PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode = NORMAL_MODE, AttributeType aLoopType = ATTR_NONE); Line *mFirstLine, *mLastLine; // The first and last lines in the linked list. Line *mFirstStaticLine, *mLastStaticLine; // The first and last static var initializer. Label *mFirstLabel, *mLastLabel; // The first and last labels in the linked list. Func **mFunc; // Binary-searchable array of functions. int mFuncCount, mFuncCountMax; Line *mTempLine; // for use with dll Execute # Naveen N9 Label *mTempLabel; // for use with dll Execute # Naveen N9 Func *mTempFunc; // for use with dll Execute # Naveen N9 ahkx_int_str xifwinactive ; // ahkx N11 context sensitivity ahkx_int_str xwingetid ; // ahkx_int_str_str xsend ; // ahksend // Naveen moved above from private Line *mCurrLine; // Seems better to make this public than make Line our friend. Label *mPlaceholderLabel; // Used in place of a NULL label to simplify code. #ifndef MINIDLL TCHAR mThisMenuItemName[MAX_MENU_NAME_LENGTH + 1]; TCHAR mThisMenuName[MAX_MENU_NAME_LENGTH + 1]; LPTSTR mThisHotkeyName, mPriorHotkeyName; #endif HWND mNextClipboardViewer; bool mOnClipboardChangeIsRunning; Label *mOnClipboardChangeLabel, *mOnExitLabel; // The label to run when the script terminates (NULL if none). ExitReasons mExitReason; ScriptTimer *mFirstTimer, *mLastTimer; // The first and last script timers in the linked list. UINT mTimerCount, mTimerEnabledCount; #ifndef MINIDLL UserMenu *mFirstMenu, *mLastMenu; UINT mMenuCount; #endif DWORD mThisHotkeyStartTime, mPriorHotkeyStartTime; // Tickcount timestamp of when its subroutine began. #ifndef MINIDLL TCHAR mEndChar; // The ending character pressed to trigger the most recent non-auto-replace hotstring. #endif 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 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. bool mIsReadyToExecute; bool mAutoExecSectionIsRunning; bool mIsRestart; // The app is restarting rather than starting from scratch. bool mIsAutoIt2; // Whether this script is considered to be an AutoIt2 script. bool mErrorStdOut; // true if load-time syntax errors should be sent to stdout vs. a MsgBox. #ifdef AUTOHOTKEYSC bool mCompiledHasCustomIcon; // Whether the compiled script uses a custom icon. #else TextStream *mIncludeLibraryFunctionsThenExit; #endif __int64 mLinesExecutedThisCycle; // Use 64-bit to match the type of g->LinesPerCycle int mUninterruptedLineCountMax; // 32-bit for performance (since huge values seem unnecessary here). int mUninterruptibleTime; DWORD mLastScriptRest, mLastPeekTime; CStringW mRunAsUser, mRunAsPass, mRunAsDomain; #ifndef MINIDLL 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. #endif #ifdef _USRDLL void Destroy(); // HotKeyIt H1 destroy script #endif ResultType Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance,bool aIsText); // ResultType InitDll(global_struct &g,HINSTANCE hInstance); // HotKeyIt init dll from text ResultType CreateWindows(); #ifndef MINIDLL void EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags); void CreateTrayIcon(); void UpdateTrayIcon(bool aForceUpdate = false); #endif ResultType AutoExecSection(); #ifndef MINIDLL ResultType Edit(); #endif ResultType Reload(bool aDisplayErrors); ResultType ExitApp(ExitReasons aExitReason, LPTSTR aBuf = NULL, int ExitCode = 0); void TerminateApp(ExitReasons aExitReason, int aExitCode); // L31: Added aExitReason. See script.cpp. #ifdef AUTOHOTKEYSC LineNumberType LoadFromFile(); #else LineNumberType LoadFromFile(bool aScriptWasNotspecified); #endif #ifndef AUTOHOTKEYSC LineNumberType LoadFromText(LPTSTR aScript); // HotKeyIt H1 load text instead file ahktextdll ResultType LoadIncludedText(LPTSTR aFileSpec); //New read text #endif ResultType LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure); ResultType UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable , bool aUpdatePriorityOnly); ResultType DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]); #ifndef AUTOHOTKEYSC Func *FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude); #endif Func *FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength = 0, int *apInsertPos = NULL); Func *AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject = NULL); ResultType DefineClass(LPTSTR aBuf); ResultType DefineClassVars(LPTSTR aBuf, bool aStatic); Object *FindClass(LPCTSTR aClassName, size_t aClassNameLength = 0); int AddBIF(LPTSTR aFuncName, BuiltInFunctionType bif, size_t minparams, size_t maxparams); // N10 added for dynamic BIFs #define FINDVAR_DEFAULT (VAR_LOCAL | VAR_GLOBAL) #define FINDVAR_GLOBAL VAR_GLOBAL #define FINDVAR_LOCAL VAR_LOCAL #define FINDVAR_STATIC (VAR_LOCAL | VAR_LOCAL_STATIC) Var *FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength = 0, int aScope = FINDVAR_DEFAULT); Var *FindVar(LPTSTR aVarName, size_t aVarNameLength = 0, int *apInsertPos = NULL , int aScope = FINDVAR_DEFAULT , bool *apIsLocal = NULL); Var *AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope); static void *GetVarType(LPTSTR aVarName); WinGroup *FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound = false); ResultType AddGroup(LPTSTR aGroupName); Label *FindLabel(LPTSTR aLabelName); ResultType DoRunAs(LPTSTR aCommandLine, LPTSTR aWorkingDir, bool aDisplayErrors, bool aUpdateLastError, WORD aShowWindow , Var *aOutputVar, PROCESS_INFORMATION &aPI, bool &aSuccess, HANDLE &aNewProcess, LPTSTR aSystemErrorText); ResultType ActionExec(LPTSTR aAction, LPTSTR aParams = NULL, LPTSTR aWorkingDir = NULL , bool aDisplayErrors = true, LPTSTR aRunShowMode = NULL, HANDLE *aProcess = NULL , bool aUpdateLastError = false, bool aUseRunAs = false, Var *aOutputVar = NULL); #ifndef MINIDLL LPTSTR ListVars(LPTSTR aBuf, int aBufSize); LPTSTR ListKeyHistory(LPTSTR aBuf, int aBufSize); ResultType PerformMenu(LPTSTR aMenu, LPTSTR aCommand, LPTSTR aParam3, LPTSTR aParam4, LPTSTR aOptions, LPTSTR aOptions2); // L17: Added aOptions2 for Icon sub-command (icon width). Arg was previously reserved/unused. UserMenu *FindMenu(LPTSTR aMenuName); UserMenu *AddMenu(LPTSTR aMenuName); ResultType ScriptDeleteMenu(UserMenu *aMenu); UserMenuItem *FindMenuItemByID(UINT aID) { UserMenuItem *mi; for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu) for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem) if (mi->mMenuID == 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; } ResultType PerformGui(LPTSTR aBuf, LPTSTR aControlType, LPTSTR aOptions, LPTSTR aParam4); static GuiType *ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName = NULL, size_t *aNameLength = NULL); #endif // Call this SciptError to avoid confusion with Line's error-displaying functions: ResultType ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // , ResultType aErrorType = FAIL); void ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo = _T(""), Line *line = NULL); void WarnUninitializedVar(Var *var); void MaybeWarnLocalSameAsGlobal(Func &func, Var &var); void PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount); static ResultType UnhandledException(ExprTokenType*& aToken, Line* aLine); static ResultType SetErrorLevelOrThrow() { return SetErrorLevelOrThrowBool(true); } static ResultType SetErrorLevelOrThrowBool(bool aError); static ResultType SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat); static ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat = NULL, LPCTSTR aExtraInfo = _T("")); static void FreeExceptionToken(ExprTokenType*& 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 // //////////////////////// VarSizeType BIV_True_False(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName); #endif //#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts. VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName); //#endif VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName); +VarSizeType BIV_CoordMode(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName); // HotKeyIt H1 path of loaded dll VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName); // Handles various variables. VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScreenWidth_Height(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptHwnd(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineNumber(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileExt(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IPAddress(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsAdmin(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName); //////////////////////// // BUILT-IN FUNCTIONS // //////////////////////// // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. #define EXPR_TOKEN_LENGTH(token_raw, token_as_string) \ ( (token_raw->symbol == SYM_VAR && !token_raw->var->IsBinaryClip()) \ ? token_raw->var->Length()\ : _tcslen(token_as_string) ) #ifdef ENABLE_DLLCALL bool IsDllArgTypeName(LPTSTR name); void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free = NULL); BIF_DECL(BIF_DllCall); BIF_DECL(BIF_DynaCall); #endif BIF_DECL(BIF_Struct); BIF_DECL(BIF_sizeof); BIF_DECL(BIF_FindFunc); BIF_DECL(BIF_FindLabel); BIF_DECL(BIF_Getvar); BIF_DECL(BIF_Static); BIF_DECL(BIF_Alias); BIF_DECL(BIF_CacheEnable); BIF_DECL(BIF_getTokenValue); BIF_DECL(BIF_ResourceLoadLibrary); BIF_DECL(BIF_MemoryLoadLibrary); BIF_DECL(BIF_MemoryGetProcAddress); BIF_DECL(BIF_MemoryFreeLibrary); BIF_DECL(BIF_Lock); BIF_DECL(BIF_TryLock); BIF_DECL(BIF_UnLock); BIF_DECL(BIF_StrLen); BIF_DECL(BIF_SubStr); BIF_DECL(BIF_InStr); BIF_DECL(BIF_RegEx); BIF_DECL(BIF_Asc); BIF_DECL(BIF_Chr); BIF_DECL(BIF_NumGet); BIF_DECL(BIF_NumPut); BIF_DECL(BIF_StrGetPut); BIF_DECL(BIF_IsLabel); BIF_DECL(BIF_IsFunc); BIF_DECL(BIF_Func); BIF_DECL(BIF_IsByRef); BIF_DECL(BIF_GetKeyState); BIF_DECL(BIF_GetKeyName); BIF_DECL(BIF_VarSetCapacity); BIF_DECL(BIF_FileExist); BIF_DECL(BIF_WinExistActive); BIF_DECL(BIF_Round); BIF_DECL(BIF_FloorCeil); 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_Exp); BIF_DECL(BIF_SqrtLogLn); BIF_DECL(BIF_OnMessage); #ifdef ENABLE_REGISTERCALLBACK BIF_DECL(BIF_RegisterCallback); #endif #ifndef MINIDLL BIF_DECL(BIF_StatusBar); BIF_DECL(BIF_LV_GetNextOrCount); BIF_DECL(BIF_LV_GetText); BIF_DECL(BIF_LV_AddInsertModify); BIF_DECL(BIF_LV_Delete); BIF_DECL(BIF_LV_InsertModifyDeleteCol); BIF_DECL(BIF_LV_SetImageList); BIF_DECL(BIF_TV_AddModifyDelete); BIF_DECL(BIF_TV_GetRelatedItem); BIF_DECL(BIF_TV_Get); BIF_DECL(BIF_TV_SetImageList); BIF_DECL(BIF_IL_Create); BIF_DECL(BIF_IL_Destroy); BIF_DECL(BIF_IL_Add); #endif BIF_DECL(BIF_Trim); // L31: Also handles LTrim and RTrim. BIF_DECL(BIF_IsObject); BIF_DECL(BIF_ObjCreate); BIF_DECL(BIF_ObjArray); BIF_DECL(BIF_CriticalObject); BIF_DECL(BIF_sizeof); BIF_DECL(BIF_Struct); BIF_DECL(BIF_ObjInvoke); // Pseudo-operator. See script_object.cpp for comments. BIF_DECL(BIF_ObjGetInPlace); // Pseudo-operator. BIF_DECL(BIF_ObjNew); // Pseudo-operator. BIF_DECL(BIF_ObjIncDec); // Pseudo-operator. BIF_DECL(BIF_ObjAddRefRelease); // 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_ObjInsert); BIF_DECL(BIF_ObjRemove); BIF_DECL(BIF_ObjGetCapacity); BIF_DECL(BIF_ObjSetCapacity); BIF_DECL(BIF_ObjGetAddress); BIF_DECL(BIF_ObjMaxIndex); BIF_DECL(BIF_ObjMinIndex); BIF_DECL(BIF_ObjNewEnum); BIF_DECL(BIF_ObjHasKey); BIF_DECL(BIF_ObjClone); // Advanced file IO interfaces BIF_DECL(BIF_FileOpen); BIF_DECL(BIF_ComObjActive); BIF_DECL(BIF_ComObjCreate); BIF_DECL(BIF_ComObjGet); BIF_DECL(BIF_ComObjMemDll); BIF_DECL(BIF_ComObjDll); BIF_DECL(BIF_ComObjConnect); BIF_DECL(BIF_ComObjError); BIF_DECL(BIF_ComObjTypeOrValue); BIF_DECL(BIF_ComObjFlags); BIF_DECL(BIF_ComObjArray); BIF_DECL(BIF_ComObjQuery); BIF_DECL(BIF_Exception); BOOL LegacyResultToBOOL(LPTSTR aResult); BOOL LegacyVarToBOOL(Var &aVar); BOOL TokenToBOOL(ExprTokenType &aToken, SymbolType aTokenIsNumber); SymbolType TokenIsPureNumeric(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken, BOOL aWarnUninitializedVar); // Same as TokenIsEmptyString but optionally warns if the token is an uninitialized var. __int64 TokenToInt64(ExprTokenType &aToken, BOOL aIsPureInteger = FALSE); double TokenToDouble(ExprTokenType &aToken, BOOL aCheckForHex = TRUE, BOOL aIsPureFloat = FALSE); LPTSTR TokenToString(ExprTokenType &aToken, LPTSTR aBuf = NULL); ResultType TokenToDoubleOrInt64(ExprTokenType &aToken); IObject *TokenToObject(ExprTokenType &aToken); // L31 Func *TokenToFunc(ExprTokenType &aToken); ResultType TokenSetResult(ExprTokenType &aResultToken, LPCTSTR aResult, size_t aResultLength = -1); LPTSTR RegExMatch(LPTSTR aHaystack, LPTSTR aNeedleRegEx); void SetWorkingDir(LPTSTR aNewDir); int ConvertJoy(LPTSTR aBuf, int *aJoystickID = NULL, bool aAllowOnlyButtons = false); bool ScriptGetKeyState(vk_type aVK, KeyStateTypes aKeyStateType); double ScriptGetJoyState(JoyControls aJoy, int aJoystickID, ExprTokenType &aToken, bool aUseBoolForUpDown); #endif diff --git a/source/script2.cpp b/source/script2.cpp index 87218a9..981ac1c 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -10519,1039 +10519,1046 @@ int Line::ConvertEscapeChar(LPTSTR aFilespec) size_t Line::ConvertEscapeCharGetLine(LPTSTR aBuf, int aMaxCharsToRead, FILE *fp) { if (!aBuf || !fp) return -1; if (aMaxCharsToRead < 1) return 0; if (feof(fp)) return -1; // Previous call to this function probably already read the last line. if (_fgetts(aBuf, aMaxCharsToRead, fp) == NULL) // end-of-file or error { *aBuf = '\0'; // Reset since on error, contents added by _fgetts() are indeterminate. return -1; } return _tcslen(aBuf); } #endif // The functions above are not needed by the self-contained version. bool Line::FileIsFilteredOut(WIN32_FIND_DATA &aCurrentFile, FileLoopModeType aFileLoopMode , LPTSTR aFilePath, size_t aFilePathLength) // Caller has ensured that aFilePath (if non-blank) has a trailing backslash. { if (aCurrentFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // It's a folder. { if (aFileLoopMode == FILE_LOOP_FILES_ONLY || aCurrentFile.cFileName[0] == '.' && (!aCurrentFile.cFileName[1] // Relies on short-circuit boolean order. || aCurrentFile.cFileName[1] == '.' && !aCurrentFile.cFileName[2])) // return true; // Exclude this folder by returning true. } else // it's not a folder. if (aFileLoopMode == FILE_LOOP_FOLDERS_ONLY) return true; // Exclude this file by returning true. // Since file was found, also prepend the file's path to its name for the caller: if (*aFilePath) { // Seems best to check length in advance because it allows a faster move/copy method further below // (in lieu of sntprintf(), which is probably quite a bit slower than the method here). size_t name_length = _tcslen(aCurrentFile.cFileName); if (aFilePathLength + name_length >= MAX_PATH) // v1.0.45.03: Filter out filenames that would be truncated because it seems undesirable in 99% of // cases to include such "faulty" data in the loop. Most scripts would want to skip them rather than // seeing the truncated names. Furthermore, a truncated name might accidentally match the name // of a legitimate non-truncated filename, which could cause such a name to get retrieved twice by // the loop (or other undesirable side-effects). return true; //else no overflow is possible, so below can move things around inside the buffer without concern. tmemmove(aCurrentFile.cFileName + aFilePathLength, aCurrentFile.cFileName, name_length + 1); // memmove() because source & dest might overlap. +1 to include the terminator. tmemcpy(aCurrentFile.cFileName, aFilePath, aFilePathLength); // Prepend in the area liberated by the above. Don't include the terminator since this is a concat operation. } return false; // Indicate that this file is not to be filtered out. } Label *Line::GetJumpTarget(bool aIsDereferenced) { LPTSTR target_label = aIsDereferenced ? ARG1 : RAW_ARG1; Label *label = g_script.FindLabel(target_label); if (!label) { LineError(ERR_NO_LABEL, FAIL, target_label); return NULL; } if (!aIsDereferenced) mRelatedLine = (Line *)label; // The script loader has ensured that label->mJumpToLine isn't NULL. // else don't update it, because that would permanently resolve the jump target, and we want it to stay dynamic. // Seems best to do this even for GOSUBs even though it's a bit weird: return IsJumpValid(*label); // Any error msg was already displayed by the above call. } Label *Line::IsJumpValid(Label &aTargetLabel, bool aSilent) // Returns aTargetLabel is the jump is valid, or NULL otherwise. { // aTargetLabel can be NULL if this Goto's target is the physical end of the script. // And such a destination is always valid, regardless of where aOrigin is. // UPDATE: It's no longer possible for the destination of a Goto or Gosub to be // NULL because the script loader has ensured that the end of the script always has // an extra ACT_EXIT that serves as an anchor for any final labels in the script: //if (aTargetLabel == NULL) // return OK; // The above check is also necessary to avoid dereferencing a NULL pointer below. Line *parent_line_of_label_line; if ( !(parent_line_of_label_line = aTargetLabel.mJumpToLine->mParentLine) ) // A Goto/Gosub can always jump to a point anywhere in the outermost layer // (i.e. outside all blocks) without restriction: return &aTargetLabel; // Indicate success. // So now we know this Goto/Gosub is attempting to jump into a block somewhere. Is that // block a legal place to jump?: for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine) if (parent_line_of_label_line == ancestor) // Since aTargetLabel is in the same block as the Goto line itself (or a block // that encloses that block), it's allowed: return &aTargetLabel; // Indicate success. // This can happen if the Goto's target is at a deeper level than it, or if the target // is at a more shallow level but is in some block totally unrelated to it! // Returns FAIL by default, which is what we want because that value is zero: if (!aSilent) LineError(_T("A Goto/Gosub must not jump into a block that doesn't enclose it.")); // Omit GroupActivate from the error msg since that is rare enough to justify the increase in common-case clarity. return NULL; } BOOL Line::IsOutsideAnyFunctionBody() // v1.0.48.02 { for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine) if (ancestor->mAttribute == ATTR_TRUE && ancestor->mActionType == ACT_BLOCK_BEGIN) // Ordered for short-circuit performance. return FALSE; // ATTR_TRUE marks an open-brace as belonging to a function's body, so indicate this this line is inside a function. return TRUE; // Indicate that this line is not inside any function body. } //////////////////////// // BUILT-IN VARIABLES // //////////////////////// VarSizeType BIV_True_False(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = aVarName[4] ? '0': '1'; *aBuf = '\0'; } return 1; // The length of the value. } VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR format_str; switch(ctoupper(aVarName[2])) { // Use the case-sensitive formats required by GetDateFormat(): case 'M': format_str = (aVarName[5] ? _T("MMMM") : _T("MMM")); break; case 'D': format_str = (aVarName[5] ? _T("dddd") : _T("ddd")); break; } // Confirmed: The below will automatically use the local time (not UTC) when 3rd param is NULL. return (VarSizeType)(GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, format_str, aBuf, aBuf ? 999 : 0) - 1); } VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return 6; // Since only an estimate is needed in this mode, return the maximum length of any item. aVarName += 2; // Skip past the "A_". // The current time is refreshed only if it's been a certain number of milliseconds since // the last fetch of one of these built-in time variables. This keeps the variables in // sync with one another when they are used consecutively such as this example: // Var = %A_Hour%:%A_Min%:%A_Sec% // Using GetTickCount() because it's very low overhead compared to the other time functions: static DWORD sLastUpdate = 0; // Static should be thread + recursion safe in this case. static SYSTEMTIME sST = {0}; // Init to detect when it's empty. BOOL is_msec = !_tcsicmp(aVarName, _T("MSec")); // Always refresh if it's milliseconds, for better accuracy. DWORD now_tick = GetTickCount(); if (is_msec || now_tick - sLastUpdate > 50 || !sST.wYear) // See comments above. { GetLocalTime(&sST); sLastUpdate = now_tick; } if (is_msec) return _stprintf(aBuf, _T("%03d"), sST.wMilliseconds); TCHAR second_letter = ctoupper(aVarName[1]); switch(ctoupper(aVarName[0])) { case 'Y': switch(second_letter) { case 'D': // A_YDay return _stprintf(aBuf, _T("%d"), GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear))); case 'W': // A_YWeek return GetISOWeekNumber(aBuf, sST.wYear , GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear)) , sST.wDayOfWeek); default: // A_Year/A_YYYY return _stprintf(aBuf, _T("%d"), sST.wYear); } // No break because all cases above return: //break; case 'M': switch(second_letter) { case 'D': // A_MDay (synonymous with A_DD) return _stprintf(aBuf, _T("%02d"), sST.wDay); case 'I': // A_Min return _stprintf(aBuf, _T("%02d"), sST.wMinute); default: // A_MM and A_Mon (A_MSec was already completely handled higher above). return _stprintf(aBuf, _T("%02d"), sST.wMonth); } // No break because all cases above return: //break; case 'D': // A_DD (synonymous with A_MDay) return _stprintf(aBuf, _T("%02d"), sST.wDay); case 'W': // A_WDay return _stprintf(aBuf, _T("%d"), sST.wDayOfWeek + 1); case 'H': // A_Hour return _stprintf(aBuf, _T("%02d"), sST.wHour); case 'S': // A_Sec (A_MSec was already completely handled higher above). return _stprintf(aBuf, _T("%02d"), sST.wSecond); } return 0; // Never reached, but avoids compiler warning. } VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName) { // The BatchLine value can be either a numerical string or a string that ends in "ms". TCHAR buf[256]; LPTSTR target_buf = aBuf ? aBuf : buf; if (g->IntervalBeforeRest > -1) // Have this new method take precedence, if it's in use by the script. return _stprintf(target_buf, _T("%dms"), g->IntervalBeforeRest); // Not sntprintf(). // Otherwise: ITOA64(g->LinesPerCycle, target_buf); return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName) { if (g->TitleMatchMode == FIND_REGEX) // v1.0.45. { if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here: _tcscpy(aBuf, _T("RegEx")); return 5; // The length. } // Otherwise, it's a numerical mode: // It's done this way in case it's ever allowed to go beyond a single-digit number. TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->TitleMatchMode, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here: _tcscpy(aBuf, g->TitleFindFast ? _T("Fast") : _T("Slow")); return 4; // Always length 4 } VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenWindows ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenText ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->AutoTrim ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->StringCaseSense == SCS_INSENSITIVE ? _T("Off") // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : (g->StringCaseSense == SCS_SENSITIVE ? _T("On") : _T("Locale")))) : 6; // Room for On, Off, or Locale (in the estimation phase). } VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g->FormatInt; *aBuf = '\0'; } return 1; } VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return (VarSizeType)_tcslen(g->FormatFloat); // Include the extra chars since this is just an estimate. LPTSTR str_with_leading_percent_omitted = g->FormatFloat + 1; size_t length = _tcslen(str_with_leading_percent_omitted); tcslcpy(aBuf, str_with_leading_percent_omitted , length + !(length && str_with_leading_percent_omitted[length-1] == 'f')); // Omit the trailing character only if it's an 'f', not any other letter such as the 'e' in "%0.6e" (for backward compatibility). return (VarSizeType)_tcslen(aBuf); // Must return exact length when aBuf isn't NULL. } VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->KeyDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->WinDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->ControlDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->MouseDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->DefaultMouseSpeed, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical. { // Although A_IsPaused could indicate how many threads are paused beneath the current thread, // that would be a problem because it would yield a non-zero value even when the underlying thread // isn't paused (i.e. other threads below it are paused), which would defeat the original purpose. // In addition, A_IsPaused probably won't be commonly used, so it seems best to keep it simple. // NAMING: A_IsPaused seems to be a better name than A_Pause or A_Paused due to: // Better readability. // Consistent with A_IsSuspended, which is strongly related to pause/unpause. // The fact that it wouldn't be likely for a function to turn off pause then turn it back on // (or vice versa), which was the main reason for storing "Off" and "On" in things like // A_DetectHiddenWindows. if (aBuf) { // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is // called by the AutoExec section or a threadless callback running in thread #0. *aBuf++ = (g > g_array && g[-1].IsPaused) ? '1' : '0'; *aBuf = '\0'; } return 1; } VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical. { if (!aBuf) // Return conservative estimate in case Critical status can ever change between the 1st and 2nd calls to this function. return MAX_INTEGER_LENGTH; // It seems more useful to return g->PeekFrequency than "On" or "Off" (ACT_CRITICAL ensures that // g->PeekFrequency!=0 whenever g->ThreadIsCritical==true). Also, the word "Is" in "A_IsCritical" // implies a value that can be used as a boolean such as "if A_IsCritical". if (g->ThreadIsCritical) return (VarSizeType)_tcslen(UTOA(g->PeekFrequency, aBuf)); // ACT_CRITICAL ensures that g->PeekFrequency > 0 when critical is on. // Otherwise: *aBuf++ = '0'; *aBuf = '\0'; return 1; // Caller might rely on receiving actual length when aBuf!=NULL. } #ifndef MINIDLL VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g_IsSuspended ? '1' : '0'; *aBuf = '\0'; } return 1; } #endif #ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts. VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; } #else VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName) { if (!g_hResource) { if (aBuf) *aBuf = '\0'; return 0; } else if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; } #endif VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName) { #ifdef UNICODE if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; #else // v1.1.06: A_IsUnicode is defined so that it does not cause warnings with #Warn enabled, // but left empty to encourage compatibility with older versions and AutoHotkey Basic. // This prevents scripts from using expressions like A_IsUnicode+1, which would succeed // if A_IsUnicode is 0 or 1 but fail if it is "". This change has side-effects similar // to those described for A_IsCompiled above. if (aBuf) *aBuf = '\0'; return 0; #endif } VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName) { // A similar section may be found under "case Encoding:" in FileObject::Invoke. Maintain that with this: switch (g->Encoding) { case CP_ACP: if (aBuf) *aBuf = '\0'; return 0; #define FILEENCODING_CASE(n, s) \ case n: \ if (aBuf) \ _tcscpy(aBuf, _T(s)); \ return _countof(_T(s)) - 1; // Returning readable strings for these seems more useful than returning their numeric values, especially with CP_AHKNOBOM: FILEENCODING_CASE(CP_UTF8, "UTF-8") FILEENCODING_CASE(CP_UTF8 | CP_AHKNOBOM, "UTF-8-RAW") FILEENCODING_CASE(CP_UTF16, "UTF-16") FILEENCODING_CASE(CP_UTF16 | CP_AHKNOBOM, "UTF-16-RAW") #undef FILEENCODING_CASE default: { TCHAR buf[MAX_INTEGER_SIZE + 2]; // + 2 for "CP" LPTSTR target_buf = aBuf ? aBuf : buf; target_buf[0] = _T('C'); target_buf[1] = _T('P'); _itot(g->Encoding, target_buf + 2, 10); // Always output as decimal since we aren't exactly returning a number. return (VarSizeType)_tcslen(target_buf); } } } VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName) { LPCTSTR value; switch (g->RegView) { case KEY_WOW64_32KEY: value = _T("32"); break; case KEY_WOW64_64KEY: value = _T("64"); break; default: value = _T("Default"); break; } if (aBuf) _tcscpy(aBuf, value); return (VarSizeType)_tcslen(value); } VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->LastError, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64((LONGLONG)g, aBuf)) : MAX_INTEGER_LENGTH; } VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64((LONGLONG)&g_script, aBuf)) : MAX_INTEGER_LENGTH; } VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hInstance, aBuf)) - : MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. + : MAX_INTEGER_LENGTH; } VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = (g_hInstance == GetModuleHandle(NULL)) ? '0' : '1'; *aBuf = '\0'; } return 1; } +VarSizeType BIV_CoordMode(LPTSTR aBuf, LPTSTR aVarName) +{ + return aBuf + ? (VarSizeType)_tcslen(ITOA64(((g->CoordMode >> Line::ConvertCoordModeCmd(aVarName + 11)) & COORD_MODE_MASK), aBuf)) + : MAX_INTEGER_LENGTH; +} + VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { // Return size in bytes of a pointer in the current build. *aBuf++ = '0' + sizeof(void *); *aBuf = '\0'; } return 1; } #ifndef MINIDLL VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g_NoTrayIcon ? '1' : '0'; *aBuf = '\0'; } return 1; // Length is always 1. } VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return g_script.mTrayIconTip ? (VarSizeType)_tcslen(g_script.mTrayIconTip) : 0; if (g_script.mTrayIconTip) return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mTrayIconTip)); else { *aBuf = '\0'; return 0; } } VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return g_script.mCustomIconFile ? (VarSizeType)_tcslen(g_script.mCustomIconFile) : 0; if (g_script.mCustomIconFile) return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mCustomIconFile)); else { *aBuf = '\0'; return 0; } } VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; if (!g_script.mCustomIconNumber) // Yield an empty string rather than the digit "0". { *target_buf = '\0'; return 0; } return (VarSizeType)_tcslen(UTOA(g_script.mCustomIconNumber, target_buf)); } VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName) { const int bufSize = 32; if (!aBuf) return bufSize; *aBuf = '\0'; // Init for error & not-found cases int validEventCount = 0; // Start at the current event (offset 1) for (int iOffset = 1; iOffset <= g_MaxHistoryKeys; ++iOffset) { // Get index for circular buffer int i = (g_KeyHistoryNext + g_MaxHistoryKeys - iOffset) % g_MaxHistoryKeys; // Keep looking until we hit the second valid event if (g_KeyHistory[i].event_type != _T('i') && ++validEventCount > 1) { // Find the next most recent key-down if (!g_KeyHistory[i].key_up) { GetKeyName(g_KeyHistory[i].vk, g_KeyHistory[i].sc, aBuf, bufSize); break; } } } return (VarSizeType)_tcslen(aBuf); } #endif VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR str; switch(g_script.mExitReason) { case EXIT_LOGOFF: str = _T("Logoff"); break; case EXIT_SHUTDOWN: str = _T("Shutdown"); break; // Since the below are all relatively rare, except WM_CLOSE perhaps, they are all included // as one word to cut down on the number of possible words (it's easier to write OnExit // routines to cover all possibilities if there are fewer of them). case EXIT_WM_QUIT: case EXIT_CRITICAL: case EXIT_DESTROY: case EXIT_WM_CLOSE: str = _T("Close"); break; case EXIT_ERROR: str = _T("Error"); break; case EXIT_MENU: str = _T("Menu"); break; // Standard menu, not a user-defined menu. case EXIT_EXIT: str = _T("Exit"); break; // ExitApp or Exit command. case EXIT_RELOAD: str = _T("Reload"); break; case EXIT_SINGLEINSTANCE: str = _T("Single"); break; default: // EXIT_NONE or unknown value (unknown would be considered a bug if it ever happened). str = _T(""); } if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName) { // Really old comment: // A_Space is a built-in variable rather than using an escape sequence such as `s, because the escape // sequence method doesn't work (probably because `s resolves to a space and is trimmed at some point // prior to when it can be used): if (aBuf) { *aBuf++ = aVarName[5] ? ' ' : '\t'; // A_Tab[] *aBuf = '\0'; } return 1; } VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, T_AHK_VERSION); return (VarSizeType)_tcslen(T_AHK_VERSION); } VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41. { #ifdef AUTOHOTKEYSC if (aBuf) { size_t length; if (length = GetAHKInstallDir(aBuf)) // Name "AutoHotkey.exe" is assumed for code size reduction and because it's not stored in the registry: tcslcpy(aBuf + length, _T("\\AutoHotkey.exe"), MAX_PATH - length); // strlcpy() in case registry has a path that is too close to MAX_PATH to fit AutoHotkey.exe //else leave it blank as documented. return (VarSizeType)_tcslen(aBuf); } // Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the // first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail // of the destination up through the limit of its capacity (due to calling strncpy, which does this). return MAX_PATH; #else TCHAR buf[MAX_PATH]; VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, MAX_PATH); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one. return length; #endif } VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll { TCHAR buf[MAX_PATH]; VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf)); if (length == 0) VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, _countof(buf)); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one. return length; } VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64(GetTickCount(), aBuf)) : MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. } VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return DATE_FORMAT_LENGTH; SYSTEMTIME st; if (aVarName[5]) // A_Now[U]TC GetSystemTime(&st); else GetLocalTime(&st); SystemTimeToYYYYMMDD(aBuf, st); return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR type = g_os.IsWinNT() ? _T("WIN32_NT") : _T("WIN32_WINDOWS"); if (aBuf) _tcscpy(aBuf, type); return (VarSizeType)_tcslen(type); // Return length of type, not aBuf. } VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName) { LPCTSTR version = _T(""); // Init in case OS is something later than Win8. if (g_os.IsWinNT()) // "NT" includes all NT-kernel OSes: NT4/2000/XP/2003/Vista/7. { if (g_os.IsWinXP()) version = _T("WIN_XP"); else if (g_os.IsWin7()) version = _T("WIN_7"); else if (g_os.IsWin8()) version = _T("WIN_8"); else if (g_os.IsWinVista()) version = _T("WIN_VISTA"); else if (g_os.IsWin2003()) version = _T("WIN_2003"); else { if (g_os.IsWin2000()) version = _T("WIN_2000"); else if (g_os.IsWinNT4()) version = _T("WIN_NT4"); } } else { if (g_os.IsWin95()) version = _T("WIN_95"); else { if (g_os.IsWin98()) version = _T("WIN_98"); else version = _T("WIN_ME"); } } if (aBuf) _tcscpy(aBuf, version); return (VarSizeType)_tcslen(version); // Always return the length of version, not aBuf. } VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = IsOS64Bit() ? '1' : '0'; *aBuf = '\0'; } return 1; } VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName) // Registry locations from J-Paul Mesnage. { TCHAR buf[MAX_PATH]; VarSizeType length; if (g_os.IsWinNT()) // NT/2k/XP+ length = g_os.IsWin2000orLater() ? ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("InstallLanguage"), buf, MAX_PATH) : ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("Default"), buf, MAX_PATH); // NT4 else // Win9x { length = ReadRegString(HKEY_USERS, _T(".DEFAULT\\Control Panel\\Desktop\\ResourceLocale"), _T(""), buf, MAX_PATH); if (length > 3) { length -= 4; memmove(buf, buf + 4, length + 1); // +1 to include the zero terminator. } } if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). return length; } VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; // Doesn't use MAX_COMPUTERNAME_LENGTH + 1 in case longer names are allowed in the future. DWORD buf_size = MAX_PATH; // Below: A_Computer[N]ame (N is the 11th char, index 10, which if present at all distinguishes between the two). if ( !(aVarName[10] ? GetComputerName(buf, &buf_size) : GetUserName(buf, &buf_size)) ) *buf = '\0'; if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the ones here. return (VarSizeType)_tcslen(buf); // I seem to remember that the lengths returned from the above API calls aren't consistent in these cases. } VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName) { // Use GetCurrentDirectory() vs. g_WorkingDir because any in-progress FileSelectFile() // dialog is able to keep functioning even when it's quasi-thread is suspended. The // dialog can thus change the current directory as seen by the active quasi-thread even // though g_WorkingDir hasn't been updated. It might also be possible for the working // directory to change in unusual circumstances such as a network drive being lost). // // Fix for v1.0.43.11: Changed size below from 9999 to MAX_PATH, otherwise it fails sometimes on Win9x. // Testing shows that the failure is not caused by GetCurrentDirectory() writing to the unused part of the // buffer, such as zeroing it (which is good because that would require this part to be redesigned to pass // the actual buffer size or use a temp buffer). So there's something else going on to explain why the // problem only occurs in longer scripts on Win98se, not in trivial ones such as Var=%A_WorkingDir%. // Nor did the problem affect expression assignments such as Var:=A_WorkingDir. TCHAR buf[MAX_PATH]; VarSizeType length = GetCurrentDirectory(MAX_PATH, buf); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return length; // Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above: //return aBuf // ? GetCurrentDirectory(MAX_PATH, aBuf) // : GetCurrentDirectory(0, NULL); // MSDN says that this is a valid way to call it on all OSes, and testing shows that it works on WinXP and 98se. // Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; VarSizeType length = GetWindowsDirectory(buf, MAX_PATH); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return length; // Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above: //TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf. //// Sizes/lengths/-1/return-values/etc. have been verified correct. //return aBuf // ? GetWindowsDirectory(aBuf, MAX_PATH) // MAX_PATH is kept in case it's needed on Win9x for reasons similar to those in GetEnvironmentVarWin9x(). // : GetWindowsDirectory(buf_temp, 0); // Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; VarSizeType length = GetTempPath(MAX_PATH, buf); if (aBuf) { _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. if (length) { aBuf += length - 1; if (*aBuf == '\\') // For some reason, it typically yields a trailing backslash, so omit it to improve friendliness/consistency. { *aBuf = '\0'; --length; } } } return length; } VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf. // Sizes/lengths/-1/return-values/etc. have been verified correct. return aBuf ? GetEnvVarReliable(_T("comspec"), aBuf) // v1.0.46.08: GetEnvVarReliable() fixes %Comspec% on Windows 9x. : GetEnvironmentVariable(_T("comspec"), buf_temp, 0); // Avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; // One caller relies on this being explicitly limited to MAX_PATH. int aFolder; switch (ctoupper(aVarName[2])) { case 'P': // A_[P]rogram... case 'O': // Pr[o]gramFiles if (ctoupper(aVarName[9]) == 'S') // A_Programs(Common) aFolder = aVarName[10] ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS; else // A_Program[F]iles or ProgramFi[L]es aFolder = CSIDL_PROGRAM_FILES; break; case 'A': // A_AppData(Common) aFolder = aVarName[9] ? CSIDL_COMMON_APPDATA : CSIDL_APPDATA; break; case 'D': // A_Desktop(Common) aFolder = aVarName[9] ? CSIDL_COMMON_DESKTOPDIRECTORY : CSIDL_DESKTOPDIRECTORY; break; case 'S': if (ctoupper(aVarName[7]) == 'M') // A_Start[M]enu(Common) aFolder = aVarName[11] ? CSIDL_COMMON_STARTMENU : CSIDL_STARTMENU; else // A_Startup(Common) aFolder = aVarName[9] ? CSIDL_COMMON_STARTUP : CSIDL_STARTUP; break; #ifdef _DEBUG default: MsgBox(_T("DEBUG: Unhandled SpecialFolderPath variable.")); #endif } if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK) *buf = '\0'; if (aBuf) _tcscpy(aBuf, buf); // Must be done as a separate copy because SHGetFolderPath requires a buffer of length MAX_PATH, and aBuf is usually smaller. return _tcslen(buf); } VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers. { TCHAR buf[MAX_PATH]; if (SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK) *buf = '\0'; // Since it is common (such as in networked environments) to have My Documents on the root of a drive // (such as a mapped drive letter), remove the backslash from something like M:\ because M: is more // appropriate for most uses: VarSizeType length = (VarSizeType)strip_trailing_backslash(buf); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). return length; } VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return MAX_INTEGER_LENGTH; // Conservative, both for performance and in case the value changes between first and second call. // These static variables are used to keep the X and Y coordinates in sync with each other, as a snapshot // of where the caret was at one precise instant in time. This is because the X and Y vars are resolved // separately by the script, and due to split second timing, they might otherwise not be accurate with // respect to each other. This method also helps performance since it avoids unnecessary calls to // ATTACH_THREAD_INPUT. static HWND sForeWinPrev = NULL; static DWORD sTimestamp = GetTickCount(); static POINT sPoint; static BOOL sResult; // I believe only the foreground window can have a caret position due to relationship with focused control. HWND target_window = GetForegroundWindow(); // Variable must be named target_window for ATTACH_THREAD_INPUT. if (!target_window) // No window is in the foreground, report blank coordinate. { *aBuf = '\0'; return 0; } DWORD now_tick = GetTickCount(); if (target_window != sForeWinPrev || now_tick - sTimestamp > 5) // Different window or too much time has passed. { // Otherwise: ATTACH_THREAD_INPUT sResult = GetCaretPos(&sPoint); HWND focused_control = GetFocus(); // Also relies on threads being attached. DETACH_THREAD_INPUT if (!sResult) { *aBuf = '\0'; return 0; } // Unconditionally convert to screen coordinates, for simplicity. ClientToScreen(focused_control ? focused_control : target_window, &sPoint); // Now convert back to whatever is expected for the current mode. POINT origin = {0}; CoordToScreen(origin, COORD_MODE_CARET); sPoint.x -= origin.x; sPoint.y -= origin.y; // Now that all failure conditions have been checked, update static variables for the next caller: sForeWinPrev = target_window; sTimestamp = now_tick; } else // Same window and recent enough, but did prior call fail? If so, provide a blank result like the prior. { if (!sResult) { *aBuf = '\0'; return 0; } } // Now the above has ensured that sPoint contains valid coordinates that are up-to-date enough to be used. _itot(ctoupper(aVarName[7]) == 'X' ? sPoint.x : sPoint.y, aBuf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return SMALL_STRING_LENGTH; // We're returning the length of the var's contents, not the size. // Must fetch it at runtime, otherwise the program can't even be launched on Windows 95: typedef BOOL (WINAPI *MyGetCursorInfoType)(PCURSORINFO); static MyGetCursorInfoType MyGetCursorInfo = (MyGetCursorInfoType)GetProcAddress(GetModuleHandle(_T("user32")), "GetCursorInfo"); HCURSOR current_cursor; if (MyGetCursorInfo) // v1.0.42.02: This method is used to avoid ATTACH_THREAD_INPUT, which interferes with double-clicking if called repeatedly at a high frequency. { CURSORINFO ci; ci.cbSize = sizeof(CURSORINFO); current_cursor = MyGetCursorInfo(&ci) ? ci.hCursor : NULL; } else // Windows 95 and old-service-pack versions of NT4 require the old method. { POINT point; GetCursorPos(&point); HWND target_window = WindowFromPoint(point); // MSDN docs imply that threads must be attached for GetCursor() to work. // A side-effect of attaching threads or of GetCursor() itself is that mouse double-clicks // are interfered with, at least if this function is called repeatedly at a high frequency. ATTACH_THREAD_INPUT current_cursor = GetCursor(); DETACH_THREAD_INPUT } if (!current_cursor) { #define CURSOR_UNKNOWN _T("Unknown") tcslcpy(aBuf, CURSOR_UNKNOWN, SMALL_STRING_LENGTH + 1); return (VarSizeType)_tcslen(aBuf);
tinku99/ahkdll
2d0f1f23247d5f15000f882c3ad2514ea43516ab
Added A_ModuleHandle A_IsDll A_ScriptStruct A_GlobalStruct
diff --git a/source/script.cpp b/source/script.cpp index 696c6d9..228d1b5 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -10822,1024 +10822,1029 @@ Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, i { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } } else // !search_static && !search_local { var = mVar; right = mVarCount - 1; // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } if (!search_local) { var = mLazyVar; right = mLazyVarCount - 1; } if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below). { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } } // Since above didn't return, no match was found and "left" always contains the position where aVarName // should be inserted to keep the list sorted. The item is always inserted into the lazy list unless // there is no lazy list. // Set the output parameter, if present: if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below. *apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order. if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match. *apIsLocal = search_local; // Since no match was found, if this is a local fall back to searching the list of globals at runtime // if the caller didn't insist on a particular type: if (search_local && aScope == FINDVAR_DEFAULT) { // In this case, callers want to fall back to globals when a local wasn't found. However, // they want the insertion (if our caller will be doing one) to insert according to the // current assume-mode. Therefore, if the mode is assume-global, pass the apIsLocal // and apInsertPos variables to FindVar() so that it will update them to be global. if (g.CurrentFunc->mDefaultVarType == VAR_DECLARE_GLOBAL) return FindVar(aVarName, aVarNameLength, apInsertPos, FINDVAR_GLOBAL, apIsLocal); // v1: Each *dynamic* variable reference may resolve to a global if one exists. if (mIsReadyToExecute) return FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL); // Otherwise, caller only wants globals which are declared in *this* function: for (int i = 0; i < g.CurrentFunc->mGlobalVarCount; ++i) if (!_tcsicmp(var_name, g.CurrentFunc->mGlobalVar[i]->mName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return g.CurrentFunc->mGlobalVar[i]; // As a last resort, check for a super-global: Var *gvar = FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL, NULL); if (gvar && gvar->IsSuperGlobal()) return gvar; } // Otherwise, since above didn't return: return NULL; // No match. } Var *Script::AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope) // Returns the address of the new variable or NULL on failure. // Caller must ensure that g->CurrentFunc!=NULL whenever aIsLocal!=0. // Caller must ensure that aVarName isn't NULL and that this isn't a duplicate variable name. // In addition, it has provided aInsertPos, which is the insertion point so that the list stays sorted. // Finally, aIsLocal has been provided to indicate which list, global or local, should receive this // new variable, as well as the type of local variable. (See the declaration of VAR_LOCAL etc.) { if (!*aVarName) // Should never happen, so just silently indicate failure. return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); if (aVarNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Variable name too long."), aVarName); return NULL; } // Make a temporary copy that includes only the first aVarNameLength characters from aVarName: TCHAR var_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(var_name, aVarName, aVarNameLength + 1); // See explanation above. +1 to convert length to size. if (!Var::ValidateName(var_name)) // Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit). return NULL; bool aIsLocal = (aScope & VAR_LOCAL); // Not necessary or desirable to add built-in variables to a function's list of locals. Always keep // built-in vars in the global list for efficiency and to keep them out of ListVars. Note that another // section at loadtime displays an error for any attempt to explicitly declare built-in variables as // either global or local. void *var_type = GetVarType(var_name); if (aIsLocal && (var_type != (void *)VAR_NORMAL || !_tcsicmp(var_name, _T("ErrorLevel")))) // Attempt to create built-in variable as local. { if ( !(aScope & VAR_LOCAL_FUNCPARAM) ) // It's not a UDF's parameter, so fall back to the global built-in variable of this name rather than displaying an error. return FindOrAddVar(var_name, aVarNameLength, FINDVAR_GLOBAL); // Force find-or-create of global. else // (aIsLocal & VAR_LOCAL_FUNCPARAM), which means "this is a local variable and a function's parameter". { ScriptError(_T("Illegal parameter name."), aVarName); // Short message since so rare. return NULL; } } // Allocate some dynamic memory to pass to the constructor: LPTSTR new_name = SimpleHeap::Malloc(var_name, aVarNameLength); if (!new_name) // It already displayed the error for us. return NULL; // Below specifically tests for VAR_LOCAL and excludes other non-zero values/flags: // VAR_LOCAL_FUNCPARAM should not be made static. // VAR_LOCAL_STATIC is already static. // VAR_DECLARED indicates mDefaultVarType is irrelevant. if (aScope == VAR_LOCAL && g->CurrentFunc->mDefaultVarType == VAR_DECLARE_STATIC) // v1.0.48: Lexikos: Current function is assume-static, so set static attribute. aScope |= VAR_LOCAL_STATIC; bool aIsStatic = aIsLocal ? (aScope & VAR_LOCAL_STATIC) : false; Var *the_new_var = new Var(new_name, var_type, aScope); if (the_new_var == NULL) { ScriptError(ERR_OUTOFMEM); return NULL; } // If there's a lazy var list, aInsertPos provided by the caller is for it, so this new variable // always gets inserted into that list because there's always room for one more (because the // previously added variable would have purged it if it had reached capacity). Var **lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar); int &lazy_var_count = aIsStatic ? g->CurrentFunc->mStaticLazyVarCount : (aIsLocal ? g->CurrentFunc->mLazyVarCount : mLazyVarCount); // Used further below too. if (lazy_var) { if (aInsertPos != lazy_var_count) // Need to make room at the indicated position for this variable. memmove(lazy_var + aInsertPos + 1, lazy_var + aInsertPos, (lazy_var_count - aInsertPos) * sizeof(Var *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. lazy_var[aInsertPos] = the_new_var; ++lazy_var_count; // In a testing creating between 200,000 and 400,000 variables, using a size of 1000 vs. 500 improves // the speed by 17%, but when you subtract out the binary search time (leaving only the insert time), // the increase is more like 34%. But there is a diminishing return after that: Going to 2000 only // gains 20%, and to 4000 only gains an addition 10%. Therefore, to conserve memory in functions that // have so many variables that the lazy list is used, a good trade-off seems to be 2000 (8 KB of memory) // per function that needs it. #define MAX_LAZY_VARS 2000 // Don't make this larger than 90000 without altering the incremental increase of alloc_count further below. if (lazy_var_count < MAX_LAZY_VARS) // The lazy list hasn't yet reached capacity, so no need to merge it into the main list. return the_new_var; } // Since above didn't return, either there is no lazy list or the lazy list is full and needs to be // merged into the main list. // Create references to whichever variable list (local or global) is being acted upon. These // references simplify the code: Var **&var = aIsStatic ? g->CurrentFunc->mStaticVar : (aIsLocal ? g->CurrentFunc->mVar : mVar); // This needs to be a ref. too in case it needs to be realloc'd. int &var_count = aIsStatic ? g->CurrentFunc->mStaticVarCount : (aIsLocal ? g->CurrentFunc->mVarCount : mVarCount); int &var_count_max = aIsStatic ? g->CurrentFunc->mStaticVarCountMax : (aIsLocal ? g->CurrentFunc->mVarCountMax : mVarCountMax); int alloc_count; // Since the above would have returned if the lazy list is present but not yet full, if the left side // of the OR below is false, it also means that lazy_var is NULL. Thus lazy_var==NULL is implicit for the // right side of the OR: if ((lazy_var && var_count + MAX_LAZY_VARS > var_count_max) || var_count == var_count_max) { // Increase by orders of magnitude each time because realloc() is probably an expensive operation // in terms of hurting performance. So here, a little bit of memory is sacrificed to improve // the expected level of performance for scripts that use hundreds of thousands of variables. if (!var_count_max) alloc_count = aIsLocal ? 100 : 1000; // 100 conserves memory since every function needs such a block, and most functions have much fewer than 100 local variables. else if (var_count_max < 1000) alloc_count = 1000; else if (var_count_max < 9999) // Making this 9999 vs. 10000 allows an exact/whole number of lazy_var blocks to fit into main indices between 10000 and 99999 alloc_count = 9999; else if (var_count_max < 100000) { alloc_count = 100000; // This is also the threshold beyond which the lazy list is used to accelerate performance. // Create the permanent lazy list: Var **&lazy_var = aIsStatic ? g->CurrentFunc->mStaticLazyVar : (aIsLocal ? g->CurrentFunc->mLazyVar : mLazyVar); if ( !(lazy_var = (Var **)malloc(MAX_LAZY_VARS * sizeof(Var *))) ) { ScriptError(ERR_OUTOFMEM); return NULL; } } else if (var_count_max < 1000000) alloc_count = 1000000; else alloc_count = var_count_max + 1000000; // i.e. continue to increase by 4MB (1M*4) each time. Var **temp = (Var **)realloc(var, alloc_count * sizeof(Var *)); // If passed NULL, realloc() will do a malloc(). if (!temp) { ScriptError(ERR_OUTOFMEM); return NULL; } var = temp; var_count_max = alloc_count; } if (!lazy_var) { if (aInsertPos != var_count) // Need to make room at the indicated position for this variable. memmove(var + aInsertPos + 1, var + aInsertPos, (var_count - aInsertPos) * sizeof(Var *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. var[aInsertPos] = the_new_var; ++var_count; return the_new_var; } //else the variable was already inserted into the lazy list, so the above is not done. // Since above didn't return, the lazy list is not only present, but full because otherwise it // would have returned higher above. // Since the lazy list is now at its max capacity, merge it into the main list (if the // main list was at capacity, this section relies upon the fact that the above already // increased its capacity by an amount far larger than the number of items contained // in the lazy list). // LAZY LIST: Although it's not nearly as good as hashing (which might be implemented in the future, // though it would be no small undertaking since it affects so many design aspects, both load-time // and runtime for scripts), this method of accelerating insertions into a binary search array is // enormously beneficial because it improves the scalability of binary-search by two orders // of magnitude (from about 100,000 variables to at least 5M). Credit for the idea goes to Lazlo. // DETAILS: // The fact that this merge operation is so much faster than total work required // to insert each one into the main list is the whole reason for having the lazy // list. In other words, the large memmove() that would otherwise be required // to insert each new variable into the main list is completely avoided. Large memmove()s // become dramatically more costly than small ones because apparently they can't fit into // the CPU cache, so the operation would take hundreds or even thousands of times longer // depending on the speed difference between main memory and CPU cache. But above and // beyond the CPU cache issue, the lazy sorting method results in vastly less memory // being moved than would have been required without it, so even if the CPU doesn't have // a cache, the lazy list method vastly increases performance for scripts that have more // than 100,000 variables, allowing at least 5 million variables to be created without a // dramatic reduction in performance. LPTSTR target_name; Var **insert_pos, **insert_pos_prev; int i, left, right, mid; // Append any items from the lazy list to the main list that are alphabetically greater than // the last item in the main list. Above has already ensured that the main list is large enough // to accept all items in the lazy list. for (i = lazy_var_count - 1, target_name = var[var_count - 1]->mName ; i > -1 && _tcsicmp(target_name, lazy_var[i]->mName) < 0 ; --i); // Above is a self-contained loop. // Now do a separate loop to append (in the *correct* order) anything found above. for (int j = i + 1; j < lazy_var_count; ++j) // Might have zero iterations. var[var_count++] = lazy_var[j]; lazy_var_count = i + 1; // The number of items that remain after moving out those that qualified. // This will have zero iterations if the above already moved them all: for (insert_pos = var + var_count, i = lazy_var_count - 1; i > -1; --i) { // Modified binary search that relies on the fact that caller has ensured a match will never // be found in the main list for each item in the lazy list: for (target_name = lazy_var[i]->mName, left = 0, right = (int)(insert_pos - var - 1); left <= right;) { mid = (left + right) / 2; if (_tcsicmp(target_name, var[mid]->mName) > 0) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. left = mid + 1; else // it must be < 0 because caller has ensured it can't be equal (i.e. that there will be no match) right = mid - 1; } // Now "left" contains the insertion point and is known to be less than var_count due to a previous // set of loops above. Make a gap there large enough to hold all items because that allows a // smaller total amount of memory to be moved by shifting the gap to the left in the main list, // gradually filling it as we go: insert_pos_prev = insert_pos; // "prev" is the now the position of the beginning of the gap, but the gap is about to be shifted left by moving memory right. insert_pos = var + left; // This is where it *would* be inserted if we weren't doing the accelerated merge. memmove(insert_pos + i + 1, insert_pos, (insert_pos_prev - insert_pos) * sizeof(Var *)); var[left + i] = lazy_var[i]; // Now insert this item at the far right side of the gap just created. } var_count += lazy_var_count; lazy_var_count = 0; // Indicate that the lazy var list is now empty. return the_new_var; } void *Script::GetVarType(LPTSTR aVarName) { // Convert to lowercase to help performance a little (it typically only helps loadtime performance because // this function is rarely called during script-runtime). TCHAR lowercase[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(lowercase, aVarName, _countof(lowercase)); // Caller should have ensured it fits, but call strlcpy() for maintainability. CharLower(lowercase); // Above: CharLower() is smaller in code size than strlwr(), but CharLower uses the OS locale and strlwr uses // the setlocal() locale (which is always the same if setlocal() is never called). However, locale // differences shouldn't affect the cases checked below; some evidence of this is at MSDN: // "CharLower always maps uppercase I to lowercase I, even when the current language is Turkish or Azeri." if (lowercase[0] != 'a' || lowercase[1] != '_') // This check helps average-case performance. { if ( !_tcscmp(lowercase, _T("true")) || !_tcscmp(lowercase, _T("false"))) return BIV_True_False; if (!_tcscmp(lowercase, _T("clipboard"))) return (void *)VAR_CLIPBOARD; if (!_tcscmp(lowercase, _T("clipboardall"))) return (void *)VAR_CLIPBOARDALL; if (!_tcscmp(lowercase, _T("comspec"))) return BIV_ComSpec; // Lacks an "A_" prefix for backward compatibility with pre-NoEnv scripts and also it's easier to type & remember. if (!_tcscmp(lowercase, _T("programfiles"))) return BIV_SpecialFolderPath; // v1.0.43.08: Added to ease the transition to #NoEnv. // Otherwise: return (void *)VAR_NORMAL; } // Otherwise, lowercase begins with "a_", so it's probably one of the built-in variables. LPTSTR lower = lowercase + 2; // Keeping the most common ones near the top helps performance a little. if (!_tcscmp(lower, _T("index"))) return BIV_LoopIndex; // A short name since it's typed so often. if ( !_tcscmp(lower, _T("mmmm")) // Long name of month. || !_tcscmp(lower, _T("mmm")) // 3-char abbrev. month name. || !_tcscmp(lower, _T("dddd")) // Name of weekday, e.g. Sunday || !_tcscmp(lower, _T("ddd")) ) // Abbrev., e.g. Sun return BIV_MMM_DDD; if ( !_tcscmp(lower, _T("yyyy")) || !_tcscmp(lower, _T("year")) // Same as above. || !_tcscmp(lower, _T("mm")) // 01 thru 12 || !_tcscmp(lower, _T("mon")) // Same || !_tcscmp(lower, _T("dd")) // 01 thru 31 || !_tcscmp(lower, _T("mday")) // Same || !_tcscmp(lower, _T("wday")) || !_tcscmp(lower, _T("yday")) || !_tcscmp(lower, _T("yweek")) || !_tcscmp(lower, _T("hour")) || !_tcscmp(lower, _T("min")) || !_tcscmp(lower, _T("sec")) || !_tcscmp(lower, _T("msec")) ) return BIV_DateTime; if (!_tcscmp(lower, _T("tickcount"))) return BIV_TickCount; if ( !_tcscmp(lower, _T("now")) || !_tcscmp(lower, _T("nowutc"))) return BIV_Now; if (!_tcscmp(lower, _T("workingdir"))) return BIV_WorkingDir; if (!_tcscmp(lower, _T("scriptname"))) return BIV_ScriptName; if (!_tcscmp(lower, _T("scriptdir"))) return BIV_ScriptDir; if (!_tcscmp(lower, _T("scriptfullpath"))) return BIV_ScriptFullPath; if (!_tcscmp(lower, _T("scripthwnd"))) return BIV_ScriptHwnd; if (!_tcscmp(lower, _T("linenumber"))) return BIV_LineNumber; if (!_tcscmp(lower, _T("linefile"))) return BIV_LineFile; //#ifdef AUTOHOTKEYSC if (!_tcscmp(lower, _T("iscompiled"))) return BIV_IsCompiled; //#endif if (!_tcscmp(lower, _T("isunicode"))) return BIV_IsUnicode; if (!_tcscmp(lower, _T("ptrsize"))) return BIV_PtrSize; if ( !_tcscmp(lower, _T("batchlines")) || !_tcscmp(lower, _T("numbatchlines"))) return BIV_BatchLines; if (!_tcscmp(lower, _T("titlematchmode"))) return BIV_TitleMatchMode; if (!_tcscmp(lower, _T("titlematchmodespeed"))) return BIV_TitleMatchModeSpeed; if (!_tcscmp(lower, _T("detecthiddenwindows"))) return BIV_DetectHiddenWindows; if (!_tcscmp(lower, _T("detecthiddentext"))) return BIV_DetectHiddenText; if (!_tcscmp(lower, _T("autotrim"))) return BIV_AutoTrim; if (!_tcscmp(lower, _T("stringcasesense"))) return BIV_StringCaseSense; if (!_tcscmp(lower, _T("formatinteger"))) return BIV_FormatInteger; if (!_tcscmp(lower, _T("formatfloat"))) return BIV_FormatFloat; if (!_tcscmp(lower, _T("keydelay"))) return BIV_KeyDelay; if (!_tcscmp(lower, _T("windelay"))) return BIV_WinDelay; if (!_tcscmp(lower, _T("controldelay"))) return BIV_ControlDelay; if (!_tcscmp(lower, _T("mousedelay"))) return BIV_MouseDelay; if (!_tcscmp(lower, _T("defaultmousespeed"))) return BIV_DefaultMouseSpeed; if (!_tcscmp(lower, _T("ispaused"))) return BIV_IsPaused; if (!_tcscmp(lower, _T("iscritical"))) return BIV_IsCritical; if (!_tcscmp(lower, _T("fileencoding"))) return BIV_FileEncoding; if (!_tcscmp(lower, _T("regview"))) return BIV_RegView; #ifndef MINIDLL if (!_tcscmp(lower, _T("issuspended"))) return BIV_IsSuspended; if (!_tcscmp(lower, _T("iconhidden"))) return BIV_IconHidden; if (!_tcscmp(lower, _T("icontip"))) return BIV_IconTip; if (!_tcscmp(lower, _T("iconfile"))) return BIV_IconFile; if (!_tcscmp(lower, _T("iconnumber"))) return BIV_IconNumber; #endif if (!_tcscmp(lower, _T("exitreason"))) return BIV_ExitReason; if (!_tcscmp(lower, _T("ostype"))) return BIV_OSType; if (!_tcscmp(lower, _T("osversion"))) return BIV_OSVersion; if (!_tcscmp(lower, _T("is64bitos"))) return BIV_Is64bitOS; if (!_tcscmp(lower, _T("language"))) return BIV_Language; if ( !_tcscmp(lower, _T("computername")) || !_tcscmp(lower, _T("username"))) return BIV_UserName_ComputerName; if (!_tcscmp(lower, _T("windir"))) return BIV_WinDir; if (!_tcscmp(lower, _T("temp"))) return BIV_Temp; // Debatably should be A_TempDir, but brevity seemed more popular with users, perhaps for heavy uses of the temp folder. if (!_tcscmp(lower, _T("mydocuments"))) return BIV_MyDocuments; if ( !_tcscmp(lower, _T("programfiles")) || !_tcscmp(lower, _T("appdata")) || !_tcscmp(lower, _T("appdatacommon")) || !_tcscmp(lower, _T("desktop")) || !_tcscmp(lower, _T("desktopcommon")) || !_tcscmp(lower, _T("startmenu")) || !_tcscmp(lower, _T("startmenucommon")) || !_tcscmp(lower, _T("programs")) || !_tcscmp(lower, _T("programscommon")) || !_tcscmp(lower, _T("startup")) || !_tcscmp(lower, _T("startupcommon"))) return BIV_SpecialFolderPath; if (!_tcscmp(lower, _T("isadmin"))) return BIV_IsAdmin; if (!_tcscmp(lower, _T("cursor"))) return BIV_Cursor; if ( !_tcscmp(lower, _T("caretx")) || !_tcscmp(lower, _T("carety"))) return BIV_Caret; if ( !_tcscmp(lower, _T("screenwidth")) || !_tcscmp(lower, _T("screenheight"))) return BIV_ScreenWidth_Height; if (!_tcsncmp(lower, _T("ipaddress"), 9)) { lower += 9; return (*lower >= '1' && *lower <= '4' && !lower[1]) // Make sure has only one more character rather than none or several (e.g. A_IPAddress1abc should not be match). ? BIV_IPAddress : (void *)VAR_NORMAL; // Otherwise it can't be a match for any built-in variable. } if (!_tcsncmp(lower, _T("loop"), 4)) { lower += 4; if (!_tcscmp(lower, _T("readline"))) return BIV_LoopReadLine; if (!_tcscmp(lower, _T("field"))) return BIV_LoopField; if (!_tcsncmp(lower, _T("file"), 4)) { lower += 4; if (!_tcscmp(lower, _T("name"))) return BIV_LoopFileName; if (!_tcscmp(lower, _T("shortname"))) return BIV_LoopFileShortName; if (!_tcscmp(lower, _T("ext"))) return BIV_LoopFileExt; if (!_tcscmp(lower, _T("dir"))) return BIV_LoopFileDir; if (!_tcscmp(lower, _T("fullpath"))) return BIV_LoopFileFullPath; if (!_tcscmp(lower, _T("longpath"))) return BIV_LoopFileLongPath; if (!_tcscmp(lower, _T("shortpath"))) return BIV_LoopFileShortPath; if (!_tcscmp(lower, _T("attrib"))) return BIV_LoopFileAttrib; if ( !_tcscmp(lower, _T("timemodified")) || !_tcscmp(lower, _T("timecreated")) || !_tcscmp(lower, _T("timeaccessed"))) return BIV_LoopFileTime; if ( !_tcscmp(lower, _T("size")) || !_tcscmp(lower, _T("sizekb")) || !_tcscmp(lower, _T("sizemb"))) return BIV_LoopFileSize; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } if (!_tcsncmp(lower, _T("reg"), 3)) { lower += 3; if (!_tcscmp(lower, _T("type"))) return BIV_LoopRegType; if (!_tcscmp(lower, _T("key"))) return BIV_LoopRegKey; if (!_tcscmp(lower, _T("subkey"))) return BIV_LoopRegSubKey; if (!_tcscmp(lower, _T("name"))) return BIV_LoopRegName; if (!_tcscmp(lower, _T("timemodified"))) return BIV_LoopRegTimeModified; // Otherwise, it can't be a match for any built-in variable: return (void *)VAR_NORMAL; } } if (!_tcscmp(lower, _T("thisfunc"))) return BIV_ThisFunc; if (!_tcscmp(lower, _T("thislabel"))) return BIV_ThisLabel; #ifndef MINIDLL if (!_tcscmp(lower, _T("thismenuitem"))) return BIV_ThisMenuItem; if (!_tcscmp(lower, _T("thismenuitempos"))) return BIV_ThisMenuItemPos; if (!_tcscmp(lower, _T("thismenu"))) return BIV_ThisMenu; if (!_tcscmp(lower, _T("thishotkey"))) return BIV_ThisHotkey; if (!_tcscmp(lower, _T("priorhotkey"))) return BIV_PriorHotkey; if (!_tcscmp(lower, _T("timesincethishotkey"))) return BIV_TimeSinceThisHotkey; if (!_tcscmp(lower, _T("timesincepriorhotkey"))) return BIV_TimeSincePriorHotkey; if (!_tcscmp(lower, _T("endchar"))) return BIV_EndChar; #endif if (!_tcscmp(lower, _T("lasterror"))) return BIV_LastError; + + if (!_tcscmp(lower, _T("globalstruct"))) return BIV_GlobalStruct; + if (!_tcscmp(lower, _T("scriptstruct"))) return BIV_ScriptStruct; + if (!_tcscmp(lower, _T("modulehandle"))) return BIV_ModuleHandle; + if (!_tcscmp(lower, _T("isdll"))) return BIV_IsDll; if (!_tcscmp(lower, _T("eventinfo"))) return BIV_EventInfo; // It's called "EventInfo" vs. "GuiEventInfo" because it applies to non-Gui events such as OnClipboardChange. #ifndef MINIDLL if (!_tcscmp(lower, _T("guicontrol"))) return BIV_GuiControl; if ( !_tcscmp(lower, _T("guicontrolevent")) // v1.0.36: A_GuiEvent was added as a synonym for A_GuiControlEvent because it seems unlikely that A_GuiEvent will ever be needed for anything: || !_tcscmp(lower, _T("guievent"))) return BIV_GuiEvent; if ( !_tcscmp(lower, _T("gui")) || !_tcscmp(lower, _T("guiwidth")) || !_tcscmp(lower, _T("guiheight")) || !_tcscmp(lower, _T("guix")) // Naming: Brevity seems more a benefit than would A_GuiEventX's improved clarity. || !_tcscmp(lower, _T("guiy"))) return BIV_Gui; // These can be overloaded if a GuiMove label or similar is ever needed. if (!_tcscmp(lower, _T("priorkey"))) return BIV_PriorKey; #endif if (!_tcscmp(lower, _T("timeidle"))) return BIV_TimeIdle; if (!_tcscmp(lower, _T("timeidlephysical"))) return BIV_TimeIdlePhysical; if ( !_tcscmp(lower, _T("space")) || !_tcscmp(lower, _T("tab"))) return BIV_Space_Tab; if (!_tcscmp(lower, _T("ahkversion"))) return BIV_AhkVersion; if (!_tcscmp(lower, _T("ahkpath"))) return BIV_AhkPath; if (!_tcscmp(lower, _T("dllpath"))) return BIV_DllPath; // Since above didn't return: return (void *)VAR_NORMAL; } WinGroup *Script::FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound) // Caller must ensure that aGroupName isn't NULL. But if it's the empty string, NULL is returned. // Returns the Group whose name matches aGroupName. If it doesn't exist, it is created if aCreateIfNotFound==true. // Thread-safety: This function is thread-safe (except when called with aCreateIfNotFound==true) even when // the main thread happens to be calling AddGroup() and changing the linked list while it's being traversed here // by the hook thread. However, any subsequent changes to this function or AddGroup() must be carefully reviewed. { if (!*aGroupName) { if (aCreateIfNotFound) // An error message must be shown in this case since or caller is about to // exit the current script thread (and we don't want it to happen silently). ScriptError(_T("Blank group name.")); return NULL; } for (WinGroup *group = mFirstGroup; group != NULL; group = group->mNextGroup) if (!_tcsicmp(group->mName, aGroupName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return group; // Match found. // Otherwise, no match found, so create a new group. if (!aCreateIfNotFound || AddGroup(aGroupName) != OK) return NULL; return mLastGroup; } ResultType Script::AddGroup(LPTSTR aGroupName) // Returns OK or FAIL. // The caller must already have verified that this isn't a duplicate group. // This function is not thread-safe because it adds an entry to the quasi-global list of window groups. // In addition, if this function is being called by one thread while another thread is calling FindGroup(), // the thread-safety notes in FindGroup() apply. { size_t aGroupName_length = _tcslen(aGroupName); if (aGroupName_length > MAX_VAR_NAME_LENGTH) return ScriptError(_T("Group name too long."), aGroupName); if (!Var::ValidateName(aGroupName, DISPLAY_NO_ERROR)) // Seems best to use same validation as var names. return ScriptError(_T("Illegal group name."), aGroupName); LPTSTR new_name = SimpleHeap::Malloc(aGroupName, aGroupName_length); if (!new_name) return FAIL; // It already displayed the error for us. // The precise method by which the follows steps are done should be thread-safe even if // some other thread calls FindGroup() in the middle of the operation. But any changes // must be carefully reviewed: WinGroup *the_new_group = new WinGroup(new_name); if (the_new_group == NULL) return ScriptError(ERR_OUTOFMEM); if (mFirstGroup == NULL) mFirstGroup = the_new_group; else mLastGroup->mNextGroup = the_new_group; // This must be done after the above: mLastGroup = the_new_group; return OK; } Line *Script::PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd, Line *aParentLine) // aFindBlockEnd should be true, only when this function is called // by itself. The end of this function relies upon this definition. // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). { // Not thread-safe, so this can only parse one script at a time. // Not a problem for the foreseeable future: static int nest_level; // Level zero is the outermost one: outside all blocks. static bool abort; if (!aParentLine) { // We were called from outside, not recursively, so init these. This is // very important if this function is ever to be called from outside // more than once, even though it isn't currently: nest_level = 0; abort = false; } int i; DerefType *deref; // Don't check aStartingLine here at top: only do it at the bottom // for its differing return values. for (Line *line = aStartingLine; line;) { // Check if any of each arg's derefs are function calls. If so, do some validation and // preprocessing to set things up for better runtime performance: for (i = 0; i < line->mArgc; ++i) // For each arg. { ArgStruct &this_arg = line->mArg[i]; // For performance and convenience. // Exclude the derefs of output and input vars from consideration, since they can't // be function calls: if (!this_arg.is_expression) // For now, only expressions are capable of calling functions. If ever change this, might want to add a check here for this_arg.type != ARG_TYPE_NORMAL (for performance). continue; if (this_arg.deref) // No function-calls are present because the expression contains neither variables nor function calls. { for (deref = this_arg.deref; deref->marker; ++deref) // For each deref. { if (!deref->is_function) continue; if ( !(deref->func = FindFunc(deref->marker, deref->length)) ) { #ifndef AUTOHOTKEYSC bool error_was_shown, file_was_found; if ( !(deref->func = FindFuncInLibrary(deref->marker, deref->length, error_was_shown, file_was_found, true)) ) { abort = true; // So that the caller doesn't also report an error. // When above already displayed the proximate cause of the error, it's usually // undesirable to show the cascade effects of that error in a second dialog: return error_was_shown ? NULL : line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); } #else abort = true; return line->PreparseError(ERR_NONEXISTENT_FUNCTION, deref->marker); #endif } // L31: Parameter counting and validation was previously done in this section, // but is now handled by ExpressionToPostfix. } // for each deref of this arg } // if (this_arg.deref) if (!line->ExpressionToPostfix(this_arg)) // At this stage, this_arg.is_expression is known to be true. Doing this here, after the script has been loaded, might improve the compactness/adjacent-ness of the compiled expressions in memory, which might improve performance due to CPU caching. { abort = true; // So that the caller doesn't also report an error. return NULL; // The function above already displayed the error msg. } } // for each arg of this line // All lines in our recursion layer are assigned to the block that the caller specified: if (line->mParentLine == NULL) // i.e. don't do it if it's already "owned" by an IF or ELSE. line->mParentLine = aParentLine; // Can be NULL. if (ACT_IS_IF_OR_ELSE_OR_LOOP(line->mActionType) || line->mActionType == ACT_REPEAT) { // In this case, the loader should have already ensured that line->mNextLine is not NULL. if (line->mNextLine->mActionType == ACT_BLOCK_BEGIN && line->mNextLine->mAttribute == ATTR_TRUE) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Improper line below this.")); // Short message since so rare. A function must not be defined directly below an IF/ELSE/LOOP because runtime evaluation won't handle it properly. } if (line->mActionType == ACT_FOR) { ASSERT(line->mArgc == 3); // Now that this FOR's expression has been pre-parsed, exclude it from mArgc so that ExpandArgs() // won't evaluate it -- PerformLoopFor() needs to call ExpandExpression() directly in order to // receive the object reference which is the result of the expression. line->mArgc--; } // Make the line immediately following each ELSE, IF or LOOP be enclosed by that stmt. // This is done to make it illegal for a Goto or Gosub to jump into a deeper layer, // such as in this example: // #y:: // ifwinexist, pad // { // goto, label1 // ifwinexist, pad // label1: // ; With or without the enclosing block, the goto would still go to an illegal place // ; in the below, resulting in an "unexpected else" error: // { // msgbox, ifaction // } ; not necessary to make this line enclosed by the if because labels can't point to it? // else // msgbox, elseaction // } // return line->mNextLine->mParentLine = line; // Go onto the IF's or ELSE's action in case it too is an IF, rather than skipping over it: line = line->mNextLine; continue; } switch (line->mActionType) { case ACT_BLOCK_BEGIN: // Some insane limit too large to ever likely be exceeded, yet small enough not // to be a risk of stack overflow when recursing in ExecUntil(). Mostly, this is // here to reduce the chance of a program crash if a binary file, a corrupted file, // or something unexpected has been loaded as a script when it shouldn't have been. // Update: Increased the limit from 100 to 1000 so that large "else if" ladders // can be constructed. Going much larger than 1000 seems unwise since ExecUntil() // will have to recurse for each nest-level, possibly resulting in stack overflow // if things get too deep: if (nest_level > 1000) { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(_T("Nesting too deep.")); // Short msg since so rare. } // Since the current convention is to store the line *after* the // BLOCK_END as the BLOCK_BEGIN's related line, that line can // be legitimately NULL if this block's BLOCK_END is the last // line in the script. So it's up to the called function // to report an error if it never finds a BLOCK_END for us. // UPDATE: The design requires that we do it here instead: ++nest_level; if (NULL == (line->mRelatedLine = PreparseBlocks(line->mNextLine, 1, line))) if (abort) // the above call already reported the error. return NULL; else { abort = true; // So that the caller doesn't also report an error. return line->PreparseError(ERR_MISSING_CLOSE_BRACE); } --nest_level; // The convention is to have the BLOCK_BEGIN's related_line // point to the line *after* the BLOCK_END. line->mRelatedLine = line->mRelatedLine->mNextLine; // Might be NULL now. // Otherwise, since any blocks contained inside this one would already // have been handled by the recursion in the above call, continue searching // from the end of this block: line = line->mRelatedLine; // If NULL, the loop-condition will catch it. break; case ACT_BLOCK_END: // Return NULL (failure) if the end was found but we weren't looking for one // (i.e. it's an orphan). Otherwise return the line after the block_end line, // which will become the caller's mRelatedLine. UPDATE: Return the // END_BLOCK line itself so that the caller can differentiate between // a NULL due to end-of-script and a NULL caused by an error: return aFindBlockEnd ? line // Doesn't seem necessary to set abort to true. : line->PreparseError(ERR_MISSING_OPEN_BRACE); default: // Continue line-by-line. line = line->mNextLine; } // switch() } // for each line // End of script has been reached. <line> is now NULL so don't attempt to dereference it. // If we were still looking for an EndBlock to match up with a begin, that's an error. // Don't report the error here because we don't know which begin-block is waiting // for an end (the caller knows and must report the error). UPDATE: Must report // the error here (see comments further above for explanation). UPDATE #2: Changed // it again: Now we let the caller handle it again: if (aFindBlockEnd) //return mLastLine->PreparseError("The script ends while a block is still open (missing })."); return NULL; // If no error, return something non-NULL to indicate success to the top-level caller. // We know we're returning to the top-level caller because aFindBlockEnd is only true // when we're recursed, and in that case the above would have returned. Thus, // we're not recursed upon reaching this line: return mLastLine; } Line *Script::PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode, AttributeType aLoopType) // Zero is the default for aMode, otherwise: // Will return NULL to the top-level caller if there's an error, or if // mLastLine is NULL (i.e. the script is empty). // Note: This function should be called with aMode == ONLY_ONE_LINE // only when aStartingLine's ActionType is something recursable such // as IF and BEGIN_BLOCK. Otherwise, it won't return after only one line. { static BOOL sInFunctionBody = FALSE; // Improves loadtime performance by allowing IsOutsideAnyFunctionBody() to be called only when necessary. // Don't check aStartingLine here at top: only do it at the bottom // for it's differing return values. Line *line_temp; AttributeType loop_type = aLoopType; for (Line *line = aStartingLine; line != NULL;) { if ( ACT_IS_IF(line->mActionType) || line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_REPEAT || line->mActionType == ACT_TRY ) { // ActionType is an IF or a LOOP or a TRY. line_temp = line->mNextLine; // line_temp is now this IF's or LOOP's or TRY's action-line. // Update: Below is commented out because it's now impossible (since all scripts end in ACT_EXIT): //if (line_temp == NULL) // This is an orphan IF/LOOP (has no action-line) at the end of the script. // return line->PreparseError(_T("Q")); // Placeholder. Formerly "This if-statement or loop has no action." // Other things rely on this check having been done, such as "if (line->mRelatedLine != NULL)": if (line_temp->mActionType == ACT_ELSE || line_temp->mActionType == ACT_BLOCK_END || line_temp->mActionType == ACT_CATCH) return line->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Lexikos: This section once maintained separate variables for file-pattern, registry, file-reading // and parsing loops. The intention seemed to be to validate certain commands such as FileAppend // differently depending on whether they're contained within a qualifying type of loop (even if some // other type of loop lies in between). However, that validation apparently wasn't implemented, // and implementing it now seems unnecessary. Doing so would also remove a useful capability: // // Loop, Read, %InputFile%, %OutputFile% // { // MyFunc(A_LoopReadLine) // } // MyFunc(line) { // ... do some processing on %line% ... // FileAppend, %line% ; This line could be considered an error, though it works in practice. // } // // Check if the IF's action-line is something we want to recurse. UPDATE: Always // recurse because other line types, such as Goto and Gosub, need to be preparsed // by this function even if they are the single-line actions of an IF or an ELSE. // Recurse this line rather than the next because we want the called function to // recurse again if this line is a ACT_BLOCK_BEGIN or is itself an IF. line_temp = PreparseIfElse(line_temp, ONLY_ONE_LINE, line->mAttribute ? line->mAttribute : loop_type); // If not end-of-script or error, line_temp is now either: // 1) If this if's/loop's action was a BEGIN_BLOCK: The line after the end of the block. // 2) If this if's/loop's action was another IF or LOOP: // a) the line after that if's else's action; or (if it doesn't have one): // b) the line after that if's/loop's action // 3) If this if's/loop's action was some single-line action: the line after that action. // In all of the above cases, line_temp is now the line where we // would expect to find an ELSE for this IF, if it has one. // Now the above has ensured that line_temp is this line's else, if it has one. // Note: line_temp will be NULL if the end of the script has been reached. // UPDATE: That can't happen now because all scripts end in ACT_EXIT: if (line_temp == NULL) // Error or end-of-script was reached. return NULL; // Seems best to keep this check for maintainability because changes to other checks can impact // whether this check will ever be "true": if (line->mRelatedLine != NULL) return line->PreparseError(_T("Q")); // Placeholder since it shouldn't happen. Formerly "This if-statement or LOOP unexpectedly already had an ELSE or end-point." // Set it to the else's action, rather than the else itself, since the else itself // is never needed during execution. UPDATE: No, instead set it to the ELSE itself // (if it has one) since we jump here at runtime when the IF is finished (whether // it's condition was true or false), thus skipping over any nested IF's that // aren't in blocks beneath it. If there's no ELSE, the below value serves as // the jumppoint we go to when the if-statement is finished. Example: // if x // if y // if z // action1 // else // action2 // action3 // x's jumppoint should be action3 so that all the nested if's // under the first one can be skipped after the "if x" line is recursively // evaluated. Because of this behavior, all IFs will have a related line // with the possibly exception of the very last if-statement in the script // (which is possible only if the script doesn't end in a Return or Exit). line->mRelatedLine = line_temp; // Even if <line> is a LOOP and line_temp and else? // Even if aMode == ONLY_ONE_LINE, an IF and its ELSE count as a single // statement (one line) due to its very nature (at least for this purpose), // so always continue on to evaluate the IF's ELSE, if present: if (line_temp->mActionType == ACT_ELSE) { if (line->mActionType == ACT_LOOP || line->mActionType == ACT_WHILE || line->mActionType == ACT_FOR || line->mActionType == ACT_TRY || line->mActionType == ACT_REPEAT) { // this can't be our else, so let the caller handle it. if (aMode != ONLY_ONE_LINE) // This ELSE was encountered while sequentially scanning the contents // of a block or at the outermost nesting layer. More thought is required // to verify this is correct. UPDATE: This check is very old and I haven't // found a case that can produce it yet, but until proven otherwise its safer // to assume it's possible. return line_temp->PreparseError(ERR_ELSE_WITH_NO_IF); // Let the caller handle this else, since it can't be ours: return line_temp; } // Now use line vs. line_temp to hold the new values, so that line_temp // stays as a marker to the ELSE line itself: line = line_temp->mNextLine; // Set it to the else's action line. // Update: The following is now impossible because all scripts end in ACT_EXIT. // Thus, it's commented out: //if (line == NULL) // An else with no action. // return line_temp->PreparseError(_T("Q")); // Placeholder since impossible. Formerly "This ELSE has no action." if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this ELSE's jumppoint. This is similar to the jumppoint set for // an ELSEless IF, so see related comments above: line_temp->mRelatedLine = line; } else if (line_temp->mActionType == ACT_UNTIL) { if (line->mActionType != ACT_LOOP && line->mActionType != ACT_FOR) // Doesn't seem useful to allow it with WHILE? { // This is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_UNTIL_WITH_NO_LOOP); return line_temp; } // Continue processing *after* UNTIL. line = line_temp->mNextLine; } else if (line_temp->mActionType == ACT_CATCH) { if (line->mActionType != ACT_TRY) { // Again, this is similar to the section above, so see there for comments. if (aMode != ONLY_ONE_LINE) return line_temp->PreparseError(ERR_CATCH_WITH_NO_TRY); return line_temp; } line = line_temp->mNextLine; if (line->mActionType == ACT_ELSE || line->mActionType == ACT_BLOCK_END || line->mActionType == ACT_CATCH) return line_temp->PreparseError(ERR_EXPECTED_BLOCK_OR_ACTION); // Assign to line rather than line_temp: line = PreparseIfElse(line, ONLY_ONE_LINE, aLoopType); if (line == NULL) return NULL; // Error or end-of-script. // Set this CATCH's jumppoint. line_temp->mRelatedLine = line; } else // line doesn't have an else, so just continue processing from line_temp's position line = line_temp; // Both cases above have ensured that line is now the first line beyond the // scope of the if-statement and that of any ELSE it may have. if (aMode == ONLY_ONE_LINE) // Return the next unprocessed line to the caller. return line; // Otherwise, continue processing at line's new location: continue; } // ActionType is "IF". // Since above didn't continue, do the switch: LPTSTR line_raw_arg1 = LINE_RAW_ARG1; // Resolve only once to help reduce code size. LPTSTR line_raw_arg2 = LINE_RAW_ARG2; // switch (line->mActionType) { case ACT_BLOCK_BEGIN: if (line->mAttribute == ATTR_TRUE) // This is the opening brace of a function definition. sInFunctionBody = TRUE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. line = PreparseIfElse(line->mNextLine, UNTIL_BLOCK_END, aLoopType); // "line" is now either NULL due to an error, or the location of the END_BLOCK itself. if (line == NULL) return NULL; // Error. break; case ACT_BLOCK_END: if (line->mAttribute == ATTR_TRUE) // This is the closing brace of a function definition. sInFunctionBody = FALSE; // Must be set only for the above condition because functions can of course contain types of blocks other than the function's own block. if (aMode == ONLY_ONE_LINE) // Syntax error. The caller would never expect this single-line to be an // end-block. UPDATE: I think this is impossible because callers only use // aMode == ONLY_ONE_LINE when aStartingLine's ActionType is already // known to be an IF or a BLOCK_BEGIN: return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (single)." if (UNTIL_BLOCK_END) // Return line rather than line->mNextLine because, if we're at the end of // the script, it's up to the caller to differentiate between that condition // and the condition where NULL is an error indicator. return line; // Otherwise, we found an end-block we weren't looking for. This should be // impossible since the block pre-parsing already balanced all the blocks? return line->PreparseError(_T("Q")); // Placeholder (see above). Formerly "Unexpected end-of-block (multi)." case ACT_BREAK: case ACT_CONTINUE: if (!aLoopType) return line->PreparseError(_T("Break/Continue must be enclosed by a Loop.")); if (line->mArgc) { if (line->ArgHasDeref(1) || line->mArg->is_expression) // It seems unlikely that computing the target loop at runtime would be useful. // For simplicity, rule out things like "break %var%" and "break % func()": return line->PreparseError(ERR_PARAM1_INVALID); //_T("Target label of Break/Continue cannot be dynamic.")); LPTSTR loop_name = line->mArg[0].text; Label *loop_label; Line *loop_line; if (IsPureNumeric(loop_name)) { int n = _ttoi(loop_name); // Find the nth innermost loop which encloses this line: for (loop_line = line->mParentLine; loop_line; loop_line = loop_line->mParentLine) if (loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) // i.e. LOOP, FOR or WHILE. if (--n < 1) break; if (!loop_line || n != 0) return line->PreparseError(ERR_PARAM1_INVALID); } else { // Target is a named loop. if ( !(loop_label = FindLabel(loop_name)) ) return line->PreparseError(ERR_NO_LABEL, loop_name); loop_line = loop_label->mJumpToLine; // Ensure the label points to a Loop, For-loop or While-loop ... if ( !(loop_line->mActionType >= ACT_LOOP && loop_line->mActionType <= ACT_WHILE) diff --git a/source/script.h b/source/script.h index 75d3835..8d1f0a3 100644 --- a/source/script.h +++ b/source/script.h @@ -2361,745 +2361,749 @@ struct GuiControlOptionsType 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_listview; // Used only for those controls that need control.union_color for something other than 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 color_changed; // To discern when a control has been put back to the default color. [v1.0.26] 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. }; LRESULT CALLBACK GuiWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK TabWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); class GuiType { public: #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 * sFont[mCurrentFontIndex].point_size) // 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 8 #define PROGRESS_DEFAULT_THICKNESS (2 * sFont[mCurrentFontIndex].point_size) LPTSTR mName; HWND mHwnd, 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 the below amount. This offset is // necessary because windows that behave like dialogs automatically return IDOK and IDCANCEL in // response to certain types of standard actions: GuiIndexType mControlCount; GuiIndexType mControlCapacity; // How many controls can fit into the current memory size of mControl. GuiControlType *mControl; // Will become an array of controls when the window is first created. GuiIndexType mDefaultButtonIndex; // Index vs. pointer is needed for some things. ULONG mReferenceCount; // For keeping this structure in memory during execution of the Gui's labels. Label *mLabelForClose, *mLabelForEscape, *mLabelForSize, *mLabelForDropFiles, *mLabelForContextMenu; bool mLabelForCloseIsRunning, mLabelForEscapeIsRunning, mLabelForSizeIsRunning; // DropFiles doesn't need one of these. bool mLabelsHaveBeenSet; DWORD mStyle, mExStyle; // Style of window. 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. TCHAR mDelimiter; // The default field delimiter when adding items to ListBox, DropDownList, ListView, etc. GuiControlType *mCurrentListView, *mCurrentTreeView; // The ListView and TreeView upon which the LV/TV functions operate. int mCurrentFontIndex; COLORREF mCurrentColor; // The default color of text in controls. COLORREF mBackgroundColorWin; // The window's background color itself. COLORREF mBackgroundColorCtl; // Background color for controls. HBRUSH mBackgroundBrushWin; // Brush corresponding to mBackgroundColorWin. HBRUSH mBackgroundBrushCtl; // Brush corresponding to mBackgroundColorCtl. 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. int mMarginX, mMarginY, mPrevX, mPrevY, mPrevWidth, mPrevHeight, mMaxExtentRight, mMaxExtentDown , mSectionX, mSectionY, mMaxExtentRightSection, mMaxExtentDownSection; LONG mMinWidth, mMinHeight, mMaxWidth, mMaxHeight; 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 mGuiShowHasNeverBeenDone, mFirstActivation, mShowIsInProgress, mDestroyWindowHasBeenCalled; bool mControlWidthWasSetByContents; // Whether the most recently added control was auto-width'd to fit its contents. #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). // Keep the default destructor to avoid entering the "Law of the Big Three": If your class requires a // copy constructor, copy assignment operator, or a destructor, then it very likely will require all three. GuiType() // Constructor : mName(NULL), mHwnd(NULL), mStatusBarHwnd(NULL), mControlCount(0), mControlCapacity(0) , mDefaultButtonIndex(-1), mLabelForClose(NULL), mLabelForEscape(NULL), mLabelForSize(NULL) , mLabelForDropFiles(NULL), mLabelForContextMenu(NULL), mReferenceCount(1) , mLabelForCloseIsRunning(false), mLabelForEscapeIsRunning(false), mLabelForSizeIsRunning(false) , mLabelsHaveBeenSet(false) // 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), mOwner(NULL), mDelimiter('|') , mCurrentFontIndex(FindOrCreateFont()) // Must call this in constructor to ensure sFont array is never NULL while a GUI object exists. Omit params to tell it to find or create DEFAULT_GUI_FONT. , mCurrentListView(NULL), mCurrentTreeView(NULL) , mTabControlCount(0), mCurrentTabControlIndex(MAX_TAB_CONTROLS), mCurrentTabIndex(0) , mCurrentColor(CLR_DEFAULT) , mBackgroundColorWin(CLR_DEFAULT), mBackgroundBrushWin(NULL) , mBackgroundColorCtl(CLR_DEFAULT), mBackgroundBrushCtl(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) { // The array of controls is left uninitialized to catch bugs. Each control's attributes should be // fully populated when it is created. //ZeroMemory(mControl, sizeof(mControl)); } static ResultType Destroy(GuiType &gui); static void DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall); // L17: Renamed function and added parameter to also handle the window's small icon. ResultType Create(); void AddRef(); void Release(); void SetLabels(LPTSTR aLabelPrefix); static void UpdateMenuBars(HMENU aMenu); ResultType AddControl(GuiControls aControlType, LPTSTR aOptions, LPTSTR aText); ResultType ParseOptions(LPTSTR aOptions, bool &aSetLastFoundWindow, ToggleValueType &aOwnDialogs, Var *&aHwndVar); void GetNonClientArea(LONG &aWidth, LONG &aHeight); void GetTotalWidthAndHeight(LONG &aWidth, LONG &aHeight); ResultType ControlParseOptions(LPTSTR aOptions, GuiControlOptionsType &aOpt, GuiControlType &aControl , GuiIndexType aControlIndex = -1); // aControlIndex is not needed upon control creation. void ControlInitOptions(GuiControlOptionsType &aOpt, GuiControlType &aControl); void ControlAddContents(GuiControlType &aControl, LPTSTR aContent, int aChoice, GuiControlOptionsType *aOpt = NULL); ResultType Show(LPTSTR aOptions, LPTSTR aTitle); ResultType Clear(); ResultType Cancel(); ResultType Close(); // Due to SC_CLOSE, etc. ResultType Escape(); // Similar to close, except typically called when the user presses ESCAPE. ResultType Submit(bool aHideIt); ResultType ControlGetContents(Var &aOutputVar, GuiControlType &aControl, LPTSTR aMode = _T("")); static VarSizeType ControlGetName(GuiType *aGuiWindow, GuiIndexType aControlIndex, LPTSTR aBuf); static GuiType *FindGui(LPTSTR aName); static GuiType *FindGui(HWND aHwnd); static GuiType *ValidGui(GuiType *&aGuiRef); // Updates aGuiRef if it points to a destroyed Gui. GuiIndexType FindControl(LPTSTR aControlID); GuiControlType *FindControl(HWND aHwnd, bool aRetrieveIndexInstead = false) { 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) // Not found yet; try again with parent. { // Since ComboBoxes (and possibly other future control types) have children, try looking // up aHwnd's parent to see if its a known control of this dialog. Some callers rely on us making // this extra effort: if (aHwnd = GetParent(aHwnd)) // 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. 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) // A match was found. return aRetrieveIndexInstead ? (GuiControlType *)(size_t)index : mControl + index; else // No match, so indicate failure. return aRetrieveIndexInstead ? (GuiControlType *)NO_CONTROL_INDEX : NULL; } int FindGroup(GuiIndexType aControlIndex, GuiIndexType &aGroupStart, GuiIndexType &aGroupEnd); ResultType SetCurrentFont(LPTSTR aOptions, LPTSTR aFontName); static int FindOrCreateFont(LPTSTR aOptions = _T(""), LPTSTR aFontName = _T(""), FontType *aFoundationFont = NULL , COLORREF *aColor = NULL); static int FindFont(FontType &aFont); void Event(GuiIndexType aControlIndex, UINT aNotifyCode, USHORT aGuiEvent = GUI_EVENT_NONE, UINT aEventInfo = 0); static WORD TextToHotkey(LPTSTR aText); static LPTSTR HotkeyToText(WORD aHotkey, LPTSTR aBuf); 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); bool ControlOverrideBkColor(GuiControlType &aControl); 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); POINT GetPositionOfTabClientArea(GuiControlType &aTabControl); ResultType SelectAdjacentTab(GuiControlType &aTabControl, bool aMoveToRight, bool aFocusFirstControl , bool aWrapAround); void ControlGetPosOfFocusedItem(GuiControlType &aControl, POINT &aPoint); static void LV_Sort(GuiControlType &aControl, int aColumnIndex, bool aSortOnlyIfEnabled, TCHAR aForceDirection = '\0'); static DWORD ControlGetListViewMode(HWND aWnd); 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); }; #endif // MINIDLL typedef NTSTATUS (NTAPI *PFN_NT_QUERY_INFORMATION_PROCESS) ( HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength OPTIONAL); typedef int (* ahkx_int_str)(LPTSTR ahkx_str); // ahkx N11 typedef int (* ahkx_int_str_str)(LPTSTR ahkx_str, LPTSTR ahkx_str2); // ahkx N11 class Script { private: #ifndef MINIDLL friend class Hotkey; #endif #ifdef CONFIG_DEBUGGER friend class Debugger; #endif public: Var **mVar, **mLazyVar; // Array of pointers-to-variable, allocated upon first use and later expanded as needed. int mVarCount, mVarCountMax, mLazyVarCount; // Count of items in the above array as well as the maximum capacity. WinGroup *mFirstGroup, *mLastGroup; // The first and last variables in the linked list. int mCurrentFuncOpenBlockCount; // While loading the script, this is how many blocks are currently open in the current function's body. bool mNextLineIsFunctionBody; // Whether the very next line to be added will be the first one of the body. #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. // 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 mNoHotkeyLabels; #ifndef MINIDLL bool mMenuUseErrorLevel; // Whether runtime errors should be displayed by the Menu command, vs. ErrorLevel. #endif #define UPDATE_TIP_FIELD tcslcpy(mNIC.szTip, (mTrayIconTip && *mTrayIconTip) ? mTrayIconTip \ : (mFileName ? mFileName : T_AHK_NAME), _countof(mNIC.szTip)); NOTIFYICONDATA mNIC; // For ease of adding and deleting our tray icon. size_t GetLine(LPTSTR aBuf, int aMaxCharsToRead, int aInContinuationSection, TextStream *ts); ResultType IsDirective(LPTSTR aBuf); ResultType ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID , ActionTypeType aOldActionType = OLD_INVALID, LPTSTR aActionName = NULL , LPTSTR aEndMarker = NULL, LPTSTR aLiteralMap = NULL, size_t aLiteralMapLength = 0); ResultType ParseDerefs(LPTSTR aArgText, LPTSTR aArgMap, DerefType *aDeref, int &aDerefCount); LPTSTR ParseActionType(LPTSTR aBufTarget, LPTSTR aBufSource, bool aDisplayErrors); static ActionTypeType ConvertActionType(LPTSTR aActionTypeString); static ActionTypeType ConvertOldActionType(LPTSTR aActionTypeString); ResultType AddLabel(LPTSTR aLabelName, bool aAllowDupe); ResultType AddLine(ActionTypeType aActionType, LPTSTR aArg[] = NULL, int aArgc = 0, LPTSTR aArgMap[] = NULL); // These aren't in the Line class because I think they're easier to implement // if aStartingLine is allowed to be NULL (for recursive calls). If they // were member functions of class Line, a check for NULL would have to // be done before dereferencing any line's mNextLine, for example: Line *PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd = false, Line *aParentLine = NULL); Line *PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode = NORMAL_MODE, AttributeType aLoopType = ATTR_NONE); Line *mFirstLine, *mLastLine; // The first and last lines in the linked list. Line *mFirstStaticLine, *mLastStaticLine; // The first and last static var initializer. Label *mFirstLabel, *mLastLabel; // The first and last labels in the linked list. Func **mFunc; // Binary-searchable array of functions. int mFuncCount, mFuncCountMax; Line *mTempLine; // for use with dll Execute # Naveen N9 Label *mTempLabel; // for use with dll Execute # Naveen N9 Func *mTempFunc; // for use with dll Execute # Naveen N9 ahkx_int_str xifwinactive ; // ahkx N11 context sensitivity ahkx_int_str xwingetid ; // ahkx_int_str_str xsend ; // ahksend // Naveen moved above from private Line *mCurrLine; // Seems better to make this public than make Line our friend. Label *mPlaceholderLabel; // Used in place of a NULL label to simplify code. #ifndef MINIDLL TCHAR mThisMenuItemName[MAX_MENU_NAME_LENGTH + 1]; TCHAR mThisMenuName[MAX_MENU_NAME_LENGTH + 1]; LPTSTR mThisHotkeyName, mPriorHotkeyName; #endif HWND mNextClipboardViewer; bool mOnClipboardChangeIsRunning; Label *mOnClipboardChangeLabel, *mOnExitLabel; // The label to run when the script terminates (NULL if none). ExitReasons mExitReason; ScriptTimer *mFirstTimer, *mLastTimer; // The first and last script timers in the linked list. UINT mTimerCount, mTimerEnabledCount; #ifndef MINIDLL UserMenu *mFirstMenu, *mLastMenu; UINT mMenuCount; #endif DWORD mThisHotkeyStartTime, mPriorHotkeyStartTime; // Tickcount timestamp of when its subroutine began. #ifndef MINIDLL TCHAR mEndChar; // The ending character pressed to trigger the most recent non-auto-replace hotstring. #endif 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 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. bool mIsReadyToExecute; bool mAutoExecSectionIsRunning; bool mIsRestart; // The app is restarting rather than starting from scratch. bool mIsAutoIt2; // Whether this script is considered to be an AutoIt2 script. bool mErrorStdOut; // true if load-time syntax errors should be sent to stdout vs. a MsgBox. #ifdef AUTOHOTKEYSC bool mCompiledHasCustomIcon; // Whether the compiled script uses a custom icon. #else TextStream *mIncludeLibraryFunctionsThenExit; #endif __int64 mLinesExecutedThisCycle; // Use 64-bit to match the type of g->LinesPerCycle int mUninterruptedLineCountMax; // 32-bit for performance (since huge values seem unnecessary here). int mUninterruptibleTime; DWORD mLastScriptRest, mLastPeekTime; CStringW mRunAsUser, mRunAsPass, mRunAsDomain; #ifndef MINIDLL 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. #endif #ifdef _USRDLL void Destroy(); // HotKeyIt H1 destroy script #endif ResultType Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance,bool aIsText); // ResultType InitDll(global_struct &g,HINSTANCE hInstance); // HotKeyIt init dll from text ResultType CreateWindows(); #ifndef MINIDLL void EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags); void CreateTrayIcon(); void UpdateTrayIcon(bool aForceUpdate = false); #endif ResultType AutoExecSection(); #ifndef MINIDLL ResultType Edit(); #endif ResultType Reload(bool aDisplayErrors); ResultType ExitApp(ExitReasons aExitReason, LPTSTR aBuf = NULL, int ExitCode = 0); void TerminateApp(ExitReasons aExitReason, int aExitCode); // L31: Added aExitReason. See script.cpp. #ifdef AUTOHOTKEYSC LineNumberType LoadFromFile(); #else LineNumberType LoadFromFile(bool aScriptWasNotspecified); #endif #ifndef AUTOHOTKEYSC LineNumberType LoadFromText(LPTSTR aScript); // HotKeyIt H1 load text instead file ahktextdll ResultType LoadIncludedText(LPTSTR aFileSpec); //New read text #endif ResultType LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure); ResultType UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable , bool aUpdatePriorityOnly); ResultType DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]); #ifndef AUTOHOTKEYSC Func *FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude); #endif Func *FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength = 0, int *apInsertPos = NULL); Func *AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject = NULL); ResultType DefineClass(LPTSTR aBuf); ResultType DefineClassVars(LPTSTR aBuf, bool aStatic); Object *FindClass(LPCTSTR aClassName, size_t aClassNameLength = 0); int AddBIF(LPTSTR aFuncName, BuiltInFunctionType bif, size_t minparams, size_t maxparams); // N10 added for dynamic BIFs #define FINDVAR_DEFAULT (VAR_LOCAL | VAR_GLOBAL) #define FINDVAR_GLOBAL VAR_GLOBAL #define FINDVAR_LOCAL VAR_LOCAL #define FINDVAR_STATIC (VAR_LOCAL | VAR_LOCAL_STATIC) Var *FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength = 0, int aScope = FINDVAR_DEFAULT); Var *FindVar(LPTSTR aVarName, size_t aVarNameLength = 0, int *apInsertPos = NULL , int aScope = FINDVAR_DEFAULT , bool *apIsLocal = NULL); Var *AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope); static void *GetVarType(LPTSTR aVarName); WinGroup *FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound = false); ResultType AddGroup(LPTSTR aGroupName); Label *FindLabel(LPTSTR aLabelName); ResultType DoRunAs(LPTSTR aCommandLine, LPTSTR aWorkingDir, bool aDisplayErrors, bool aUpdateLastError, WORD aShowWindow , Var *aOutputVar, PROCESS_INFORMATION &aPI, bool &aSuccess, HANDLE &aNewProcess, LPTSTR aSystemErrorText); ResultType ActionExec(LPTSTR aAction, LPTSTR aParams = NULL, LPTSTR aWorkingDir = NULL , bool aDisplayErrors = true, LPTSTR aRunShowMode = NULL, HANDLE *aProcess = NULL , bool aUpdateLastError = false, bool aUseRunAs = false, Var *aOutputVar = NULL); #ifndef MINIDLL LPTSTR ListVars(LPTSTR aBuf, int aBufSize); LPTSTR ListKeyHistory(LPTSTR aBuf, int aBufSize); ResultType PerformMenu(LPTSTR aMenu, LPTSTR aCommand, LPTSTR aParam3, LPTSTR aParam4, LPTSTR aOptions, LPTSTR aOptions2); // L17: Added aOptions2 for Icon sub-command (icon width). Arg was previously reserved/unused. UserMenu *FindMenu(LPTSTR aMenuName); UserMenu *AddMenu(LPTSTR aMenuName); ResultType ScriptDeleteMenu(UserMenu *aMenu); UserMenuItem *FindMenuItemByID(UINT aID) { UserMenuItem *mi; for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu) for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem) if (mi->mMenuID == 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; } ResultType PerformGui(LPTSTR aBuf, LPTSTR aControlType, LPTSTR aOptions, LPTSTR aParam4); static GuiType *ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName = NULL, size_t *aNameLength = NULL); #endif // Call this SciptError to avoid confusion with Line's error-displaying functions: ResultType ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // , ResultType aErrorType = FAIL); void ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo = _T(""), Line *line = NULL); void WarnUninitializedVar(Var *var); void MaybeWarnLocalSameAsGlobal(Func &func, Var &var); void PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount); static ResultType UnhandledException(ExprTokenType*& aToken, Line* aLine); static ResultType SetErrorLevelOrThrow() { return SetErrorLevelOrThrowBool(true); } static ResultType SetErrorLevelOrThrowBool(bool aError); static ResultType SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat); static ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat = NULL, LPCTSTR aExtraInfo = _T("")); static void FreeExceptionToken(ExprTokenType*& 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 // //////////////////////// VarSizeType BIV_True_False(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName); #endif //#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts. VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName); //#endif VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName); +VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName); +VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName); +VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName); +VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName); // HotKeyIt H1 path of loaded dll VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName); // Handles various variables. VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScreenWidth_Height(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptHwnd(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineNumber(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileExt(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IPAddress(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsAdmin(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName); //////////////////////// // BUILT-IN FUNCTIONS // //////////////////////// // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. #define EXPR_TOKEN_LENGTH(token_raw, token_as_string) \ ( (token_raw->symbol == SYM_VAR && !token_raw->var->IsBinaryClip()) \ ? token_raw->var->Length()\ : _tcslen(token_as_string) ) #ifdef ENABLE_DLLCALL bool IsDllArgTypeName(LPTSTR name); void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free = NULL); BIF_DECL(BIF_DllCall); BIF_DECL(BIF_DynaCall); #endif BIF_DECL(BIF_Struct); BIF_DECL(BIF_sizeof); BIF_DECL(BIF_FindFunc); BIF_DECL(BIF_FindLabel); BIF_DECL(BIF_Getvar); BIF_DECL(BIF_Static); BIF_DECL(BIF_Alias); BIF_DECL(BIF_CacheEnable); BIF_DECL(BIF_getTokenValue); BIF_DECL(BIF_ResourceLoadLibrary); BIF_DECL(BIF_MemoryLoadLibrary); BIF_DECL(BIF_MemoryGetProcAddress); BIF_DECL(BIF_MemoryFreeLibrary); BIF_DECL(BIF_Lock); BIF_DECL(BIF_TryLock); BIF_DECL(BIF_UnLock); BIF_DECL(BIF_StrLen); BIF_DECL(BIF_SubStr); BIF_DECL(BIF_InStr); BIF_DECL(BIF_RegEx); BIF_DECL(BIF_Asc); BIF_DECL(BIF_Chr); BIF_DECL(BIF_NumGet); BIF_DECL(BIF_NumPut); BIF_DECL(BIF_StrGetPut); BIF_DECL(BIF_IsLabel); BIF_DECL(BIF_IsFunc); BIF_DECL(BIF_Func); BIF_DECL(BIF_IsByRef); BIF_DECL(BIF_GetKeyState); BIF_DECL(BIF_GetKeyName); BIF_DECL(BIF_VarSetCapacity); BIF_DECL(BIF_FileExist); BIF_DECL(BIF_WinExistActive); BIF_DECL(BIF_Round); BIF_DECL(BIF_FloorCeil); 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_Exp); BIF_DECL(BIF_SqrtLogLn); BIF_DECL(BIF_OnMessage); #ifdef ENABLE_REGISTERCALLBACK BIF_DECL(BIF_RegisterCallback); #endif #ifndef MINIDLL BIF_DECL(BIF_StatusBar); BIF_DECL(BIF_LV_GetNextOrCount); BIF_DECL(BIF_LV_GetText); BIF_DECL(BIF_LV_AddInsertModify); BIF_DECL(BIF_LV_Delete); BIF_DECL(BIF_LV_InsertModifyDeleteCol); BIF_DECL(BIF_LV_SetImageList); BIF_DECL(BIF_TV_AddModifyDelete); BIF_DECL(BIF_TV_GetRelatedItem); BIF_DECL(BIF_TV_Get); BIF_DECL(BIF_TV_SetImageList); BIF_DECL(BIF_IL_Create); BIF_DECL(BIF_IL_Destroy); BIF_DECL(BIF_IL_Add); #endif BIF_DECL(BIF_Trim); // L31: Also handles LTrim and RTrim. BIF_DECL(BIF_IsObject); BIF_DECL(BIF_ObjCreate); BIF_DECL(BIF_ObjArray); BIF_DECL(BIF_CriticalObject); BIF_DECL(BIF_sizeof); BIF_DECL(BIF_Struct); BIF_DECL(BIF_ObjInvoke); // Pseudo-operator. See script_object.cpp for comments. BIF_DECL(BIF_ObjGetInPlace); // Pseudo-operator. BIF_DECL(BIF_ObjNew); // Pseudo-operator. BIF_DECL(BIF_ObjIncDec); // Pseudo-operator. BIF_DECL(BIF_ObjAddRefRelease); // 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_ObjInsert); BIF_DECL(BIF_ObjRemove); BIF_DECL(BIF_ObjGetCapacity); BIF_DECL(BIF_ObjSetCapacity); BIF_DECL(BIF_ObjGetAddress); BIF_DECL(BIF_ObjMaxIndex); BIF_DECL(BIF_ObjMinIndex); BIF_DECL(BIF_ObjNewEnum); BIF_DECL(BIF_ObjHasKey); BIF_DECL(BIF_ObjClone); // Advanced file IO interfaces BIF_DECL(BIF_FileOpen); BIF_DECL(BIF_ComObjActive); BIF_DECL(BIF_ComObjCreate); BIF_DECL(BIF_ComObjGet); BIF_DECL(BIF_ComObjMemDll); BIF_DECL(BIF_ComObjDll); BIF_DECL(BIF_ComObjConnect); BIF_DECL(BIF_ComObjError); BIF_DECL(BIF_ComObjTypeOrValue); BIF_DECL(BIF_ComObjFlags); BIF_DECL(BIF_ComObjArray); BIF_DECL(BIF_ComObjQuery); BIF_DECL(BIF_Exception); BOOL LegacyResultToBOOL(LPTSTR aResult); BOOL LegacyVarToBOOL(Var &aVar); BOOL TokenToBOOL(ExprTokenType &aToken, SymbolType aTokenIsNumber); SymbolType TokenIsPureNumeric(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken, BOOL aWarnUninitializedVar); // Same as TokenIsEmptyString but optionally warns if the token is an uninitialized var. __int64 TokenToInt64(ExprTokenType &aToken, BOOL aIsPureInteger = FALSE); double TokenToDouble(ExprTokenType &aToken, BOOL aCheckForHex = TRUE, BOOL aIsPureFloat = FALSE); LPTSTR TokenToString(ExprTokenType &aToken, LPTSTR aBuf = NULL); ResultType TokenToDoubleOrInt64(ExprTokenType &aToken); IObject *TokenToObject(ExprTokenType &aToken); // L31 Func *TokenToFunc(ExprTokenType &aToken); ResultType TokenSetResult(ExprTokenType &aResultToken, LPCTSTR aResult, size_t aResultLength = -1); LPTSTR RegExMatch(LPTSTR aHaystack, LPTSTR aNeedleRegEx); void SetWorkingDir(LPTSTR aNewDir); int ConvertJoy(LPTSTR aBuf, int *aJoystickID = NULL, bool aAllowOnlyButtons = false); bool ScriptGetKeyState(vk_type aVK, KeyStateTypes aKeyStateType); double ScriptGetJoyState(JoyControls aJoy, int aJoystickID, ExprTokenType &aToken, bool aUseBoolForUpDown); #endif diff --git a/source/script2.cpp b/source/script2.cpp index 4f94e8a..87218a9 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -10499,1024 +10499,1057 @@ int Line::ConvertEscapeChar(LPTSTR aFilespec) // Before the line is written, also do some conversions if the source file is known to // be an AutoIt2 script: if (aFromAutoIt2) { // This will not fix all possible uses of A_ScriptDir, just those that are dereferences. // For example, this would not be fixed: StringLen, length, a_ScriptDir StrReplace(buf, _T("%A_ScriptDir%"), _T("%A_ScriptDir%\\"), SCS_INSENSITIVE, UINT_MAX, _countof(buf)); // Later can add some other, similar conversions here. } _fputts(buf, f2); } fclose(f1); fclose(f2); MsgBox(_T("The file was successfully converted.")); return 0; // Return 0 on success in this case. } size_t Line::ConvertEscapeCharGetLine(LPTSTR aBuf, int aMaxCharsToRead, FILE *fp) { if (!aBuf || !fp) return -1; if (aMaxCharsToRead < 1) return 0; if (feof(fp)) return -1; // Previous call to this function probably already read the last line. if (_fgetts(aBuf, aMaxCharsToRead, fp) == NULL) // end-of-file or error { *aBuf = '\0'; // Reset since on error, contents added by _fgetts() are indeterminate. return -1; } return _tcslen(aBuf); } #endif // The functions above are not needed by the self-contained version. bool Line::FileIsFilteredOut(WIN32_FIND_DATA &aCurrentFile, FileLoopModeType aFileLoopMode , LPTSTR aFilePath, size_t aFilePathLength) // Caller has ensured that aFilePath (if non-blank) has a trailing backslash. { if (aCurrentFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // It's a folder. { if (aFileLoopMode == FILE_LOOP_FILES_ONLY || aCurrentFile.cFileName[0] == '.' && (!aCurrentFile.cFileName[1] // Relies on short-circuit boolean order. || aCurrentFile.cFileName[1] == '.' && !aCurrentFile.cFileName[2])) // return true; // Exclude this folder by returning true. } else // it's not a folder. if (aFileLoopMode == FILE_LOOP_FOLDERS_ONLY) return true; // Exclude this file by returning true. // Since file was found, also prepend the file's path to its name for the caller: if (*aFilePath) { // Seems best to check length in advance because it allows a faster move/copy method further below // (in lieu of sntprintf(), which is probably quite a bit slower than the method here). size_t name_length = _tcslen(aCurrentFile.cFileName); if (aFilePathLength + name_length >= MAX_PATH) // v1.0.45.03: Filter out filenames that would be truncated because it seems undesirable in 99% of // cases to include such "faulty" data in the loop. Most scripts would want to skip them rather than // seeing the truncated names. Furthermore, a truncated name might accidentally match the name // of a legitimate non-truncated filename, which could cause such a name to get retrieved twice by // the loop (or other undesirable side-effects). return true; //else no overflow is possible, so below can move things around inside the buffer without concern. tmemmove(aCurrentFile.cFileName + aFilePathLength, aCurrentFile.cFileName, name_length + 1); // memmove() because source & dest might overlap. +1 to include the terminator. tmemcpy(aCurrentFile.cFileName, aFilePath, aFilePathLength); // Prepend in the area liberated by the above. Don't include the terminator since this is a concat operation. } return false; // Indicate that this file is not to be filtered out. } Label *Line::GetJumpTarget(bool aIsDereferenced) { LPTSTR target_label = aIsDereferenced ? ARG1 : RAW_ARG1; Label *label = g_script.FindLabel(target_label); if (!label) { LineError(ERR_NO_LABEL, FAIL, target_label); return NULL; } if (!aIsDereferenced) mRelatedLine = (Line *)label; // The script loader has ensured that label->mJumpToLine isn't NULL. // else don't update it, because that would permanently resolve the jump target, and we want it to stay dynamic. // Seems best to do this even for GOSUBs even though it's a bit weird: return IsJumpValid(*label); // Any error msg was already displayed by the above call. } Label *Line::IsJumpValid(Label &aTargetLabel, bool aSilent) // Returns aTargetLabel is the jump is valid, or NULL otherwise. { // aTargetLabel can be NULL if this Goto's target is the physical end of the script. // And such a destination is always valid, regardless of where aOrigin is. // UPDATE: It's no longer possible for the destination of a Goto or Gosub to be // NULL because the script loader has ensured that the end of the script always has // an extra ACT_EXIT that serves as an anchor for any final labels in the script: //if (aTargetLabel == NULL) // return OK; // The above check is also necessary to avoid dereferencing a NULL pointer below. Line *parent_line_of_label_line; if ( !(parent_line_of_label_line = aTargetLabel.mJumpToLine->mParentLine) ) // A Goto/Gosub can always jump to a point anywhere in the outermost layer // (i.e. outside all blocks) without restriction: return &aTargetLabel; // Indicate success. // So now we know this Goto/Gosub is attempting to jump into a block somewhere. Is that // block a legal place to jump?: for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine) if (parent_line_of_label_line == ancestor) // Since aTargetLabel is in the same block as the Goto line itself (or a block // that encloses that block), it's allowed: return &aTargetLabel; // Indicate success. // This can happen if the Goto's target is at a deeper level than it, or if the target // is at a more shallow level but is in some block totally unrelated to it! // Returns FAIL by default, which is what we want because that value is zero: if (!aSilent) LineError(_T("A Goto/Gosub must not jump into a block that doesn't enclose it.")); // Omit GroupActivate from the error msg since that is rare enough to justify the increase in common-case clarity. return NULL; } BOOL Line::IsOutsideAnyFunctionBody() // v1.0.48.02 { for (Line *ancestor = mParentLine; ancestor != NULL; ancestor = ancestor->mParentLine) if (ancestor->mAttribute == ATTR_TRUE && ancestor->mActionType == ACT_BLOCK_BEGIN) // Ordered for short-circuit performance. return FALSE; // ATTR_TRUE marks an open-brace as belonging to a function's body, so indicate this this line is inside a function. return TRUE; // Indicate that this line is not inside any function body. } //////////////////////// // BUILT-IN VARIABLES // //////////////////////// VarSizeType BIV_True_False(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = aVarName[4] ? '0': '1'; *aBuf = '\0'; } return 1; // The length of the value. } VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR format_str; switch(ctoupper(aVarName[2])) { // Use the case-sensitive formats required by GetDateFormat(): case 'M': format_str = (aVarName[5] ? _T("MMMM") : _T("MMM")); break; case 'D': format_str = (aVarName[5] ? _T("dddd") : _T("ddd")); break; } // Confirmed: The below will automatically use the local time (not UTC) when 3rd param is NULL. return (VarSizeType)(GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, format_str, aBuf, aBuf ? 999 : 0) - 1); } VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return 6; // Since only an estimate is needed in this mode, return the maximum length of any item. aVarName += 2; // Skip past the "A_". // The current time is refreshed only if it's been a certain number of milliseconds since // the last fetch of one of these built-in time variables. This keeps the variables in // sync with one another when they are used consecutively such as this example: // Var = %A_Hour%:%A_Min%:%A_Sec% // Using GetTickCount() because it's very low overhead compared to the other time functions: static DWORD sLastUpdate = 0; // Static should be thread + recursion safe in this case. static SYSTEMTIME sST = {0}; // Init to detect when it's empty. BOOL is_msec = !_tcsicmp(aVarName, _T("MSec")); // Always refresh if it's milliseconds, for better accuracy. DWORD now_tick = GetTickCount(); if (is_msec || now_tick - sLastUpdate > 50 || !sST.wYear) // See comments above. { GetLocalTime(&sST); sLastUpdate = now_tick; } if (is_msec) return _stprintf(aBuf, _T("%03d"), sST.wMilliseconds); TCHAR second_letter = ctoupper(aVarName[1]); switch(ctoupper(aVarName[0])) { case 'Y': switch(second_letter) { case 'D': // A_YDay return _stprintf(aBuf, _T("%d"), GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear))); case 'W': // A_YWeek return GetISOWeekNumber(aBuf, sST.wYear , GetYDay(sST.wMonth, sST.wDay, IS_LEAP_YEAR(sST.wYear)) , sST.wDayOfWeek); default: // A_Year/A_YYYY return _stprintf(aBuf, _T("%d"), sST.wYear); } // No break because all cases above return: //break; case 'M': switch(second_letter) { case 'D': // A_MDay (synonymous with A_DD) return _stprintf(aBuf, _T("%02d"), sST.wDay); case 'I': // A_Min return _stprintf(aBuf, _T("%02d"), sST.wMinute); default: // A_MM and A_Mon (A_MSec was already completely handled higher above). return _stprintf(aBuf, _T("%02d"), sST.wMonth); } // No break because all cases above return: //break; case 'D': // A_DD (synonymous with A_MDay) return _stprintf(aBuf, _T("%02d"), sST.wDay); case 'W': // A_WDay return _stprintf(aBuf, _T("%d"), sST.wDayOfWeek + 1); case 'H': // A_Hour return _stprintf(aBuf, _T("%02d"), sST.wHour); case 'S': // A_Sec (A_MSec was already completely handled higher above). return _stprintf(aBuf, _T("%02d"), sST.wSecond); } return 0; // Never reached, but avoids compiler warning. } VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName) { // The BatchLine value can be either a numerical string or a string that ends in "ms". TCHAR buf[256]; LPTSTR target_buf = aBuf ? aBuf : buf; if (g->IntervalBeforeRest > -1) // Have this new method take precedence, if it's in use by the script. return _stprintf(target_buf, _T("%dms"), g->IntervalBeforeRest); // Not sntprintf(). // Otherwise: ITOA64(g->LinesPerCycle, target_buf); return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName) { if (g->TitleMatchMode == FIND_REGEX) // v1.0.45. { if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here: _tcscpy(aBuf, _T("RegEx")); return 5; // The length. } // Otherwise, it's a numerical mode: // It's done this way in case it's ever allowed to go beyond a single-digit number. TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->TitleMatchMode, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) // For backward compatibility (due to StringCaseSense), never change the case used here: _tcscpy(aBuf, g->TitleFindFast ? _T("Fast") : _T("Slow")); return 4; // Always length 4 } VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenWindows ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->DetectHiddenText ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->AutoTrim ? _T("On") : _T("Off"))) // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : 3; // Room for either On or Off (in the estimation phase). } VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(_tcscpy(aBuf, g->StringCaseSense == SCS_INSENSITIVE ? _T("Off") // For backward compatibility (due to StringCaseSense), never change the case used here. Fixed in v1.0.42.01 to return exact length (required). : (g->StringCaseSense == SCS_SENSITIVE ? _T("On") : _T("Locale")))) : 6; // Room for On, Off, or Locale (in the estimation phase). } VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g->FormatInt; *aBuf = '\0'; } return 1; } VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return (VarSizeType)_tcslen(g->FormatFloat); // Include the extra chars since this is just an estimate. LPTSTR str_with_leading_percent_omitted = g->FormatFloat + 1; size_t length = _tcslen(str_with_leading_percent_omitted); tcslcpy(aBuf, str_with_leading_percent_omitted , length + !(length && str_with_leading_percent_omitted[length-1] == 'f')); // Omit the trailing character only if it's an 'f', not any other letter such as the 'e' in "%0.6e" (for backward compatibility). return (VarSizeType)_tcslen(aBuf); // Must return exact length when aBuf isn't NULL. } VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->KeyDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->WinDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->ControlDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->MouseDelay, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->DefaultMouseSpeed, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical. { // Although A_IsPaused could indicate how many threads are paused beneath the current thread, // that would be a problem because it would yield a non-zero value even when the underlying thread // isn't paused (i.e. other threads below it are paused), which would defeat the original purpose. // In addition, A_IsPaused probably won't be commonly used, so it seems best to keep it simple. // NAMING: A_IsPaused seems to be a better name than A_Pause or A_Paused due to: // Better readability. // Consistent with A_IsSuspended, which is strongly related to pause/unpause. // The fact that it wouldn't be likely for a function to turn off pause then turn it back on // (or vice versa), which was the main reason for storing "Off" and "On" in things like // A_DetectHiddenWindows. if (aBuf) { // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is // called by the AutoExec section or a threadless callback running in thread #0. *aBuf++ = (g > g_array && g[-1].IsPaused) ? '1' : '0'; *aBuf = '\0'; } return 1; } VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName) // v1.0.48: Lexikos: Added BIV_IsPaused and BIV_IsCritical. { if (!aBuf) // Return conservative estimate in case Critical status can ever change between the 1st and 2nd calls to this function. return MAX_INTEGER_LENGTH; // It seems more useful to return g->PeekFrequency than "On" or "Off" (ACT_CRITICAL ensures that // g->PeekFrequency!=0 whenever g->ThreadIsCritical==true). Also, the word "Is" in "A_IsCritical" // implies a value that can be used as a boolean such as "if A_IsCritical". if (g->ThreadIsCritical) return (VarSizeType)_tcslen(UTOA(g->PeekFrequency, aBuf)); // ACT_CRITICAL ensures that g->PeekFrequency > 0 when critical is on. // Otherwise: *aBuf++ = '0'; *aBuf = '\0'; return 1; // Caller might rely on receiving actual length when aBuf!=NULL. } #ifndef MINIDLL VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g_IsSuspended ? '1' : '0'; *aBuf = '\0'; } return 1; } #endif #ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts. VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; } #else VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName) { if (!g_hResource) { if (aBuf) *aBuf = '\0'; return 0; } else if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; } #endif VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName) { #ifdef UNICODE if (aBuf) { *aBuf++ = '1'; *aBuf = '\0'; } return 1; #else // v1.1.06: A_IsUnicode is defined so that it does not cause warnings with #Warn enabled, // but left empty to encourage compatibility with older versions and AutoHotkey Basic. // This prevents scripts from using expressions like A_IsUnicode+1, which would succeed // if A_IsUnicode is 0 or 1 but fail if it is "". This change has side-effects similar // to those described for A_IsCompiled above. if (aBuf) *aBuf = '\0'; return 0; #endif } VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName) { // A similar section may be found under "case Encoding:" in FileObject::Invoke. Maintain that with this: switch (g->Encoding) { case CP_ACP: if (aBuf) *aBuf = '\0'; return 0; #define FILEENCODING_CASE(n, s) \ case n: \ if (aBuf) \ _tcscpy(aBuf, _T(s)); \ return _countof(_T(s)) - 1; // Returning readable strings for these seems more useful than returning their numeric values, especially with CP_AHKNOBOM: FILEENCODING_CASE(CP_UTF8, "UTF-8") FILEENCODING_CASE(CP_UTF8 | CP_AHKNOBOM, "UTF-8-RAW") FILEENCODING_CASE(CP_UTF16, "UTF-16") FILEENCODING_CASE(CP_UTF16 | CP_AHKNOBOM, "UTF-16-RAW") #undef FILEENCODING_CASE default: { TCHAR buf[MAX_INTEGER_SIZE + 2]; // + 2 for "CP" LPTSTR target_buf = aBuf ? aBuf : buf; target_buf[0] = _T('C'); target_buf[1] = _T('P'); _itot(g->Encoding, target_buf + 2, 10); // Always output as decimal since we aren't exactly returning a number. return (VarSizeType)_tcslen(target_buf); } } } VarSizeType BIV_RegView(LPTSTR aBuf, LPTSTR aVarName) { LPCTSTR value; switch (g->RegView) { case KEY_WOW64_32KEY: value = _T("32"); break; case KEY_WOW64_64KEY: value = _T("64"); break; default: value = _T("Default"); break; } if (aBuf) _tcscpy(aBuf, value); return (VarSizeType)_tcslen(value); } VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; _itot(g->LastError, target_buf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(target_buf); } +VarSizeType BIV_GlobalStruct(LPTSTR aBuf, LPTSTR aVarName) +{ + return aBuf + ? (VarSizeType)_tcslen(ITOA64((LONGLONG)g, aBuf)) + : MAX_INTEGER_LENGTH; +} + + +VarSizeType BIV_ScriptStruct(LPTSTR aBuf, LPTSTR aVarName) +{ + return aBuf + ? (VarSizeType)_tcslen(ITOA64((LONGLONG)&g_script, aBuf)) + : MAX_INTEGER_LENGTH; +} + + +VarSizeType BIV_ModuleHandle(LPTSTR aBuf, LPTSTR aVarName) +{ + return aBuf + ? (VarSizeType)_tcslen(ITOA64((LONGLONG)g_hInstance, aBuf)) + : MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. +} + + +VarSizeType BIV_IsDll(LPTSTR aBuf, LPTSTR aVarName) +{ + if (aBuf) + { + *aBuf++ = (g_hInstance == GetModuleHandle(NULL)) ? '0' : '1'; + *aBuf = '\0'; + } + return 1; +} VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { // Return size in bytes of a pointer in the current build. *aBuf++ = '0' + sizeof(void *); *aBuf = '\0'; } return 1; } #ifndef MINIDLL VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = g_NoTrayIcon ? '1' : '0'; *aBuf = '\0'; } return 1; // Length is always 1. } VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return g_script.mTrayIconTip ? (VarSizeType)_tcslen(g_script.mTrayIconTip) : 0; if (g_script.mTrayIconTip) return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mTrayIconTip)); else { *aBuf = '\0'; return 0; } } VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return g_script.mCustomIconFile ? (VarSizeType)_tcslen(g_script.mCustomIconFile) : 0; if (g_script.mCustomIconFile) return (VarSizeType)_tcslen(_tcscpy(aBuf, g_script.mCustomIconFile)); else { *aBuf = '\0'; return 0; } } VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; if (!g_script.mCustomIconNumber) // Yield an empty string rather than the digit "0". { *target_buf = '\0'; return 0; } return (VarSizeType)_tcslen(UTOA(g_script.mCustomIconNumber, target_buf)); } VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName) { const int bufSize = 32; if (!aBuf) return bufSize; *aBuf = '\0'; // Init for error & not-found cases int validEventCount = 0; // Start at the current event (offset 1) for (int iOffset = 1; iOffset <= g_MaxHistoryKeys; ++iOffset) { // Get index for circular buffer int i = (g_KeyHistoryNext + g_MaxHistoryKeys - iOffset) % g_MaxHistoryKeys; // Keep looking until we hit the second valid event if (g_KeyHistory[i].event_type != _T('i') && ++validEventCount > 1) { // Find the next most recent key-down if (!g_KeyHistory[i].key_up) { GetKeyName(g_KeyHistory[i].vk, g_KeyHistory[i].sc, aBuf, bufSize); break; } } } return (VarSizeType)_tcslen(aBuf); } #endif VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR str; switch(g_script.mExitReason) { case EXIT_LOGOFF: str = _T("Logoff"); break; case EXIT_SHUTDOWN: str = _T("Shutdown"); break; // Since the below are all relatively rare, except WM_CLOSE perhaps, they are all included // as one word to cut down on the number of possible words (it's easier to write OnExit // routines to cover all possibilities if there are fewer of them). case EXIT_WM_QUIT: case EXIT_CRITICAL: case EXIT_DESTROY: case EXIT_WM_CLOSE: str = _T("Close"); break; case EXIT_ERROR: str = _T("Error"); break; case EXIT_MENU: str = _T("Menu"); break; // Standard menu, not a user-defined menu. case EXIT_EXIT: str = _T("Exit"); break; // ExitApp or Exit command. case EXIT_RELOAD: str = _T("Reload"); break; case EXIT_SINGLEINSTANCE: str = _T("Single"); break; default: // EXIT_NONE or unknown value (unknown would be considered a bug if it ever happened). str = _T(""); } if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName) { // Really old comment: // A_Space is a built-in variable rather than using an escape sequence such as `s, because the escape // sequence method doesn't work (probably because `s resolves to a space and is trimmed at some point // prior to when it can be used): if (aBuf) { *aBuf++ = aVarName[5] ? ' ' : '\t'; // A_Tab[] *aBuf = '\0'; } return 1; } VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, T_AHK_VERSION); return (VarSizeType)_tcslen(T_AHK_VERSION); } VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName) // v1.0.41. { #ifdef AUTOHOTKEYSC if (aBuf) { size_t length; if (length = GetAHKInstallDir(aBuf)) // Name "AutoHotkey.exe" is assumed for code size reduction and because it's not stored in the registry: tcslcpy(aBuf + length, _T("\\AutoHotkey.exe"), MAX_PATH - length); // strlcpy() in case registry has a path that is too close to MAX_PATH to fit AutoHotkey.exe //else leave it blank as documented. return (VarSizeType)_tcslen(aBuf); } // Otherwise: Always return an estimate of MAX_PATH in case the registry entry changes between the // first call and the second. This is also relied upon by strlcpy() above, which zero-fills the tail // of the destination up through the limit of its capacity (due to calling strncpy, which does this). return MAX_PATH; #else TCHAR buf[MAX_PATH]; VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, MAX_PATH); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one. return length; #endif } VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName) // HotKeyIt H1 path of loaded dll { TCHAR buf[MAX_PATH]; VarSizeType length = (VarSizeType)GetModuleFileName(g_hInstance, buf, _countof(buf)); if (length == 0) VarSizeType length = (VarSizeType)GetModuleFileName(NULL, buf, _countof(buf)); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like this one. return length; } VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64(GetTickCount(), aBuf)) : MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. } VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return DATE_FORMAT_LENGTH; SYSTEMTIME st; if (aVarName[5]) // A_Now[U]TC GetSystemTime(&st); else GetLocalTime(&st); SystemTimeToYYYYMMDD(aBuf, st); return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR type = g_os.IsWinNT() ? _T("WIN32_NT") : _T("WIN32_WINDOWS"); if (aBuf) _tcscpy(aBuf, type); return (VarSizeType)_tcslen(type); // Return length of type, not aBuf. } VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName) { LPCTSTR version = _T(""); // Init in case OS is something later than Win8. if (g_os.IsWinNT()) // "NT" includes all NT-kernel OSes: NT4/2000/XP/2003/Vista/7. { if (g_os.IsWinXP()) version = _T("WIN_XP"); else if (g_os.IsWin7()) version = _T("WIN_7"); else if (g_os.IsWin8()) version = _T("WIN_8"); else if (g_os.IsWinVista()) version = _T("WIN_VISTA"); else if (g_os.IsWin2003()) version = _T("WIN_2003"); else { if (g_os.IsWin2000()) version = _T("WIN_2000"); else if (g_os.IsWinNT4()) version = _T("WIN_NT4"); } } else { if (g_os.IsWin95()) version = _T("WIN_95"); else { if (g_os.IsWin98()) version = _T("WIN_98"); else version = _T("WIN_ME"); } } if (aBuf) _tcscpy(aBuf, version); return (VarSizeType)_tcslen(version); // Always return the length of version, not aBuf. } VarSizeType BIV_Is64bitOS(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { *aBuf++ = IsOS64Bit() ? '1' : '0'; *aBuf = '\0'; } return 1; } VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName) // Registry locations from J-Paul Mesnage. { TCHAR buf[MAX_PATH]; VarSizeType length; if (g_os.IsWinNT()) // NT/2k/XP+ length = g_os.IsWin2000orLater() ? ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("InstallLanguage"), buf, MAX_PATH) : ReadRegString(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Nls\\Language"), _T("Default"), buf, MAX_PATH); // NT4 else // Win9x { length = ReadRegString(HKEY_USERS, _T(".DEFAULT\\Control Panel\\Desktop\\ResourceLocale"), _T(""), buf, MAX_PATH); if (length > 3) { length -= 4; memmove(buf, buf + 4, length + 1); // +1 to include the zero terminator. } } if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). return length; } VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; // Doesn't use MAX_COMPUTERNAME_LENGTH + 1 in case longer names are allowed in the future. DWORD buf_size = MAX_PATH; // Below: A_Computer[N]ame (N is the 11th char, index 10, which if present at all distinguishes between the two). if ( !(aVarName[10] ? GetComputerName(buf, &buf_size) : GetUserName(buf, &buf_size)) ) *buf = '\0'; if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the ones here. return (VarSizeType)_tcslen(buf); // I seem to remember that the lengths returned from the above API calls aren't consistent in these cases. } VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName) { // Use GetCurrentDirectory() vs. g_WorkingDir because any in-progress FileSelectFile() // dialog is able to keep functioning even when it's quasi-thread is suspended. The // dialog can thus change the current directory as seen by the active quasi-thread even // though g_WorkingDir hasn't been updated. It might also be possible for the working // directory to change in unusual circumstances such as a network drive being lost). // // Fix for v1.0.43.11: Changed size below from 9999 to MAX_PATH, otherwise it fails sometimes on Win9x. // Testing shows that the failure is not caused by GetCurrentDirectory() writing to the unused part of the // buffer, such as zeroing it (which is good because that would require this part to be redesigned to pass // the actual buffer size or use a temp buffer). So there's something else going on to explain why the // problem only occurs in longer scripts on Win98se, not in trivial ones such as Var=%A_WorkingDir%. // Nor did the problem affect expression assignments such as Var:=A_WorkingDir. TCHAR buf[MAX_PATH]; VarSizeType length = GetCurrentDirectory(MAX_PATH, buf); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return length; // Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above: //return aBuf // ? GetCurrentDirectory(MAX_PATH, aBuf) // : GetCurrentDirectory(0, NULL); // MSDN says that this is a valid way to call it on all OSes, and testing shows that it works on WinXP and 98se. // Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; VarSizeType length = GetWindowsDirectory(buf, MAX_PATH); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return length; // Formerly the following, but I don't think it's as reliable/future-proof given the 1.0.47 comment above: //TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf. //// Sizes/lengths/-1/return-values/etc. have been verified correct. //return aBuf // ? GetWindowsDirectory(aBuf, MAX_PATH) // MAX_PATH is kept in case it's needed on Win9x for reasons similar to those in GetEnvironmentVarWin9x(). // : GetWindowsDirectory(buf_temp, 0); // Above avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; VarSizeType length = GetTempPath(MAX_PATH, buf); if (aBuf) { _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. if (length) { aBuf += length - 1; if (*aBuf == '\\') // For some reason, it typically yields a trailing backslash, so omit it to improve friendliness/consistency. { *aBuf = '\0'; --length; } } } return length; } VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf_temp[1]; // Just a fake buffer to pass to some API functions in lieu of a NULL, to avoid any chance of misbehavior. Keep the size at 1 so that API functions will always fail to copy to buf. // Sizes/lengths/-1/return-values/etc. have been verified correct. return aBuf ? GetEnvVarReliable(_T("comspec"), aBuf) // v1.0.46.08: GetEnvVarReliable() fixes %Comspec% on Windows 9x. : GetEnvironmentVariable(_T("comspec"), buf_temp, 0); // Avoids subtracting 1 to be conservative and to reduce code size (due to the need to otherwise check for zero and avoid subtracting 1 in that case). } VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH]; // One caller relies on this being explicitly limited to MAX_PATH. int aFolder; switch (ctoupper(aVarName[2])) { case 'P': // A_[P]rogram... case 'O': // Pr[o]gramFiles if (ctoupper(aVarName[9]) == 'S') // A_Programs(Common) aFolder = aVarName[10] ? CSIDL_COMMON_PROGRAMS : CSIDL_PROGRAMS; else // A_Program[F]iles or ProgramFi[L]es aFolder = CSIDL_PROGRAM_FILES; break; case 'A': // A_AppData(Common) aFolder = aVarName[9] ? CSIDL_COMMON_APPDATA : CSIDL_APPDATA; break; case 'D': // A_Desktop(Common) aFolder = aVarName[9] ? CSIDL_COMMON_DESKTOPDIRECTORY : CSIDL_DESKTOPDIRECTORY; break; case 'S': if (ctoupper(aVarName[7]) == 'M') // A_Start[M]enu(Common) aFolder = aVarName[11] ? CSIDL_COMMON_STARTMENU : CSIDL_STARTMENU; else // A_Startup(Common) aFolder = aVarName[9] ? CSIDL_COMMON_STARTUP : CSIDL_STARTUP; break; #ifdef _DEBUG default: MsgBox(_T("DEBUG: Unhandled SpecialFolderPath variable.")); #endif } if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK) *buf = '\0'; if (aBuf) _tcscpy(aBuf, buf); // Must be done as a separate copy because SHGetFolderPath requires a buffer of length MAX_PATH, and aBuf is usually smaller. return _tcslen(buf); } VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers. { TCHAR buf[MAX_PATH]; if (SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK) *buf = '\0'; // Since it is common (such as in networked environments) to have My Documents on the root of a drive // (such as a mapped drive letter), remove the backslash from something like M:\ because M: is more // appropriate for most uses: VarSizeType length = (VarSizeType)strip_trailing_backslash(buf); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). return length; } VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return MAX_INTEGER_LENGTH; // Conservative, both for performance and in case the value changes between first and second call. // These static variables are used to keep the X and Y coordinates in sync with each other, as a snapshot // of where the caret was at one precise instant in time. This is because the X and Y vars are resolved // separately by the script, and due to split second timing, they might otherwise not be accurate with // respect to each other. This method also helps performance since it avoids unnecessary calls to // ATTACH_THREAD_INPUT. static HWND sForeWinPrev = NULL; static DWORD sTimestamp = GetTickCount(); static POINT sPoint; static BOOL sResult; // I believe only the foreground window can have a caret position due to relationship with focused control. HWND target_window = GetForegroundWindow(); // Variable must be named target_window for ATTACH_THREAD_INPUT. if (!target_window) // No window is in the foreground, report blank coordinate. { *aBuf = '\0'; return 0; } DWORD now_tick = GetTickCount(); if (target_window != sForeWinPrev || now_tick - sTimestamp > 5) // Different window or too much time has passed. { // Otherwise: ATTACH_THREAD_INPUT sResult = GetCaretPos(&sPoint); HWND focused_control = GetFocus(); // Also relies on threads being attached. DETACH_THREAD_INPUT if (!sResult) { *aBuf = '\0'; return 0; } // Unconditionally convert to screen coordinates, for simplicity. ClientToScreen(focused_control ? focused_control : target_window, &sPoint); // Now convert back to whatever is expected for the current mode. POINT origin = {0}; CoordToScreen(origin, COORD_MODE_CARET); sPoint.x -= origin.x; sPoint.y -= origin.y; // Now that all failure conditions have been checked, update static variables for the next caller: sForeWinPrev = target_window; sTimestamp = now_tick; } else // Same window and recent enough, but did prior call fail? If so, provide a blank result like the prior. { if (!sResult) { *aBuf = '\0'; return 0; } } // Now the above has ensured that sPoint contains valid coordinates that are up-to-date enough to be used. _itot(ctoupper(aVarName[7]) == 'X' ? sPoint.x : sPoint.y, aBuf, 10); // Always output as decimal vs. hex in this case (so that scripts can use "If var in list" with confidence). return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) return SMALL_STRING_LENGTH; // We're returning the length of the var's contents, not the size. // Must fetch it at runtime, otherwise the program can't even be launched on Windows 95: typedef BOOL (WINAPI *MyGetCursorInfoType)(PCURSORINFO); static MyGetCursorInfoType MyGetCursorInfo = (MyGetCursorInfoType)GetProcAddress(GetModuleHandle(_T("user32")), "GetCursorInfo"); HCURSOR current_cursor; if (MyGetCursorInfo) // v1.0.42.02: This method is used to avoid ATTACH_THREAD_INPUT, which interferes with double-clicking if called repeatedly at a high frequency. { CURSORINFO ci; ci.cbSize = sizeof(CURSORINFO); current_cursor = MyGetCursorInfo(&ci) ? ci.hCursor : NULL; } else // Windows 95 and old-service-pack versions of NT4 require the old method. { POINT point; GetCursorPos(&point); HWND target_window = WindowFromPoint(point); // MSDN docs imply that threads must be attached for GetCursor() to work. // A side-effect of attaching threads or of GetCursor() itself is that mouse double-clicks // are interfered with, at least if this function is called repeatedly at a high frequency. ATTACH_THREAD_INPUT current_cursor = GetCursor(); DETACH_THREAD_INPUT } if (!current_cursor) { #define CURSOR_UNKNOWN _T("Unknown")
tinku99/ahkdll
95b0f1e39f6e0160542d9aaed25978ac43e6d60b
Fixed another bug with string termination
diff --git a/source/script_struct.cpp b/source/script_struct.cpp index 53ec009..a356c10 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -947,961 +947,961 @@ ResultType STDMETHODCALLTYPE Struct::Invoke( if (objclone = Struct::Create(param,2)) { // create structure from variable Struct* tempobj = objclone->Clone(true); // resolve pointer tempobj->mStructMem = mIsPointer ? (UINT_PTR*)*target : target; tempobj->Invoke(aResultToken,aThisToken ,aFlags,aParam,aParamCount); tempobj->Release(); objclone->Release(); return OK; } return INVOKE_NOT_HANDLED; } } else // create field from structure { field = new FieldType(); deletefield = true; if (objclone == NULL) { // use this structure field->mMemAllocated = mMemAllocated; field->mIsInteger = mIsInteger; field->mIsPointer = mIsPointer; field->mEncoding = mEncoding; field->mIsUnsigned = mIsUnsigned; field->mOffset = 0; // structure with arrays so set to correct field size field->mSize = mSize / (mArraySize ? mArraySize : 1); field->mVarRef = 0; } else // use objclone created above { field->mMemAllocated = objclone->mMemAllocated; field->mIsInteger = objclone->mIsInteger; field->mIsPointer = objclone->mIsPointer; field->mEncoding = objclone->mEncoding; field->mIsUnsigned = objclone->mIsUnsigned; field->mOffset = 0; field->mSize = objclone->mSize / (objclone->mArraySize ? objclone->mArraySize : 1); } } } else if (!IS_INVOKE_CALL) // IS_INVOKE_CALL will handle the field itself field = FindField(TokenToString(*aParam[0])); } // // OPERATE ON A FIELD WITHIN THIS OBJECT // // CALL if (IS_INVOKE_CALL) { LPTSTR name = TokenToString(*aParam[0]); if (*name == '_') ++name; // ++ to exclude '_' from further consideration. ++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case. if (!_tcsicmp(name, _T("NewEnum"))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return _NewEnum(aResultToken, aParam, aParamCount); } // if first function parameter is a field get it if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0])) { if (field = FindField(TokenToString(*aParam[0]))) { // exclude parameter in aParam ++aParam; --aParamCount; } } aResultToken.symbol = SYM_INTEGER; // mostly used aResultToken.value_int64 = 0; // set default if (!_tcsicmp(name, _T("SetCapacity"))) { // Set strcuture its capacity or fields capacity if (!field) { if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { // 0 or no parameters were given to free memory if (mMemAllocated > 0) { mMemAllocated = 0; free(mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mMemAllocated > 0) free(mStructMem); // allocate memory and zero-fill if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(mStructMem,NULL,(size_t)mMemAllocated); aResultToken.value_int64 = mMemAllocated; } else mMemAllocated = 0; } else if (aParamCount) { // we must have to parmeters here since first parameter is field if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { if (field->mMemAllocated > 0) { field->mMemAllocated = 0; free(field->mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // not numeric } if (field->mMemAllocated > 0) free(field->mStructMem); // allocate memory and zero-fill if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { field->mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(field->mStructMem,NULL,(size_t)field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; aResultToken.value_int64 = mMemAllocated; } else field->mMemAllocated = 0; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetCapacity"))) { if (field) aResultToken.value_int64 = field->mMemAllocated; else aResultToken.value_int64 = mMemAllocated; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Offset"))) { if (field) aResultToken.value_int64 = field->mOffset; else if (aParamCount && TokenIsPureNumeric(*aParam[0])) // calculate size if item is an array aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("IsPointer"))) { if (field) aResultToken.value_int64 = field->mIsPointer; else aResultToken.value_int64 = mIsPointer; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Encoding"))) { if (field) aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding; else aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetPointer"))) { if (!field && aParamCount && mIsPointer) { // resolve array item if (mArraySize && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1)))); else aResultToken.value_int64 = *target; } else if (field) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset)); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Fill"))) { if (!field) // only allow to fill main structure { if (aParamCount && TokenIsPureNumeric(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize); else if (aParamCount && *TokenToString(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize); else memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetAddress"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1)); else aResultToken.value_int64 = (UINT_PTR)target; } else aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Size"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) // we do not care which item was requested because all are same size aResultToken.value_int64 = mSize / mArraySize; else aResultToken.value_int64 = mSize; } else aResultToken.value_int64 = field->mSize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("CountOf"))) { if (!field) aResultToken.value_int64 = mArraySize; else aResultToken.value_int64 = field->mArraySize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New"))) { if (!field) { if (!releaseobj) // else we have a clone already objclone = this->Clone(); } else { Struct* tempobj = objclone; if (releaseobj) // release object, it is not requred anymore { objclone = objclone->CloneField(field); tempobj->Release(); } else objclone = this->CloneField(field); } if (aParamCount) { // structure pointer and / or init object were given if (TokenIsPureNumeric(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]); objclone->mMemAllocated = 0; if (aParamCount > 1 && TokenToObject(*aParam[1])) objclone->ObjectToStruct(TokenToObject(*aParam[1])); } else if (TokenToObject(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); objclone->ObjectToStruct(TokenToObject(*aParam[0])); } } else { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); } // small fix for _New to work properly because aThisToken contains the new object if (!_tcsicmp(name, _T("_New"))) { if (aThisToken.symbol == SYM_OBJECT) aThisToken.object->Release(); else aThisToken.symbol = SYM_OBJECT; aThisToken.object = objclone; objclone->AddRef(); } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; if (deletefield) // we created the field from a structure delete field; // do not release objclone because it is returned return OK; } // For maintainability: explicitly return since above has done ++aParam, --aParamCount. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // identify that method was not found return INVOKE_NOT_HANDLED; } else if (!field) { // field was not found if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x]. else if (param_count_excluding_rvalue > 1) { // second parameter = "", so caller wants get/set field pointer if (TokenIsEmptyString(*aParam[1])) { aResultToken.symbol = SYM_INTEGER; if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) { // set simple pointer *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]); aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset); } else // set pointer to pointer { UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset; else { // get pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // clone field to object and invoke again { if (releaseobj) objclone->Release(); objclone = CloneField(field,true); /* if (!field->mArraySize && field->mIsPointer) { objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); //objclone->mIsPointer--; if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array objclone->mArraySize = 1; } else objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize)); */ objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); if (deletefield) // we created the field from a structure delete field; return OK; } } // MULTIPARAM[x,y] x[y] // SET else if (IS_INVOKE_SET) { if (field->mVarRef && TokenToObject(*aParam[1])) { // field is a structure, assign objct to structure if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer, clone to structure and invoke again if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); objclone->Release(); return OK; } // StrPut (code stolen from BIF_StrPut()) if (field->mEncoding != 65535) { // field is [T|W|U]CHAR or LP[TC]STR, set get character or string source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf); source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string)); //if (field->mSize > 2) // not [T|W|U]CHAR // source_length++; // for terminating character if (!source_length) { // Take a shortcut when source_string is empty, since some paths below might not handle it correctly. if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return { aResultToken.value_int64 = 0; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mEncoding == CP_UTF16) *(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; else *(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; aResultToken.value_int64 = 1; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } if (field->mSize > 2 && (!*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated < ((source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR))))))) { // no memory allocated yet, allocate now if (field->mMemAllocated == -1 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))){ if (deletefield) // we created the field from a structure so no memory can be allocated delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } else if (field->mMemAllocated > 0) // free previously allocated memory free(field->mStructMem); field->mMemAllocated = (source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)); // + 1 for terminating character field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; } if (field->mEncoding == UorA(CP_UTF16, CP_ACP)) tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length); else { // Conversion is required. For Unicode builds, this means encoding != CP_UTF16; #ifndef UNICODE // therefore, this section is relevant only to ANSI builds: if (field->mEncoding == CP_UTF16) { // See similar section below for comments. char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0); if (!char_count) { aResultToken.value_int64 = char_count; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). length = char_count; char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length); if (field->mSize > 2 && char_count && char_count < length) - ((LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)))[char_count++] = '\0'; + ((LPWSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[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 char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (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(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); } if (!char_count) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). // Assume there is sufficient buffer space and hope for the best: length = char_count; // Convert to target encoding. char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, 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 (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR - ((LPTSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0'; + ((LPSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0'; #ifndef UNICODE } #endif } aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = char_count; } else { switch(field->mSize) { case 4: // Listed first for performance. if (field->mIsInteger) *((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]); else // Float (32-bit). *((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]); break; case 8: if (field->mIsInteger) // v1.0.48: Support unsigned 64-bit integers like DllCall does: *((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values. ? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall(). : TokenToInt64(*aParam[1]); else // Double (64-bit). *((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]); break; case 2: *((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]); break; default: // size 1 *((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]); } //*((int*)target + field->mOffset) = (int)TokenToInt64(*aParam[1]); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TokenToInt64(*aParam[1]); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } // GET else if (field) { if (field->mArraySize || field->mVarRef) { // filed is an array or variable reference, return a structure object. if (field->mArraySize || field->mIsPointer) { // field is array or a pointer to variable objclone = CloneField(field,true); objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } else // field is refference to a variable and not pointer, create structure { Var1.symbol = SYM_STRING; Var2.symbol = SYM_VAR; Var2.var = field->mVarRef; if (TokenToObject(Var2)) { // Variable is a structure object objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target + field->mOffset; aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; } else // Variable is a string definition { Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset); if (objclone = Struct::Create(param,2)) { // create and clone object because it is created dynamically Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; tempobj->Release(); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer of main structure for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer we need to return an object if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // StrGet (code stolen from BIF_StrGet()) if (field->mEncoding != 65535) { if (field->mEncoding != UorA(CP_UTF16, CP_ACP)) { // Conversion is required. int conv_length; if (field->mSize < 4) // TCHAR or CHAR or WCHAR length = 1; #ifdef UNICODE // Convert multi-byte encoded string to UTF-16. conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length); #else CStringW wide_buf; // If the target string is not UTF-16, convert it to that first. if (field->mEncoding != CP_UTF16) { StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding); (field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString(); length = wide_buf.GetLength(); } // Now convert UTF-16 to ACP. conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // Out of memory. } conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL); #endif if (conv_length && !aResultToken.marker[conv_length - 1]) --conv_length; // Exclude null-terminator. else aResultToken.marker[conv_length] = '\0'; aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // no conversation required { if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } aResultToken.symbol = SYM_STRING; if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1)) aResultToken.marker = _T(""); } aResultToken.symbol = SYM_STRING; } else // NumGet (code stolen from BIF_NumGet()) { switch(field->mSize) { case 4: // Listed first for performance. if (!field->mIsInteger) aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset)); else if (!field->mIsUnsigned) aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above. else aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset)); break; case 8: // The below correctly copies both DOUBLE and INT64 into the union. // Unsigned 64-bit integers aren't supported because variables/expressions can't support them. aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset)); break; case 2: if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset)); break; default: // size 1 if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset)); } aResultToken.symbol = SYM_INTEGER; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // // Struct:: Internal Methods // Struct::FieldType *Struct::FindField(LPTSTR val) { for (int i = 0;i < mFieldCount;i++) { FieldType &field = mFields[i]; if (!_tcsicmp(field.key,val)) return &field; } return NULL; } bool Struct::SetInternalCapacity(IndexType new_capacity) // Expands mFields to the specified number if fields. // Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount. { FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType)); if (!new_fields) return false; mFields = new_fields; mFieldCountMax = new_capacity; return true; } ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { if (aParamCount == 0) { IObject *newenum; if (newenum = new Enumerator(this)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = newenum; } } return OK; } int Struct::Enumerator::Next(Var *aKey, Var *aVal) { if (++mOffset < mObject->mFieldCount) { FieldType &field = mObject->mFields[mOffset]; if (aKey) aKey->Assign(field.key); if (aVal) { // We need to invoke the structure to retrieve the value ExprTokenType aResultToken; // not sure about the buffer TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } else if (mOffset < mObject->mArraySize) { // structure is an array if (aKey) aKey->Assign(mOffset + 1); // mOffset starts at 1 if (aVal) { // again we need to invoke structure to retrieve the value ExprTokenType aResultToken; TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_INTEGER; aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1 mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } return false; } Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding) // Inserts a single field with the given key at the given offset. // Caller must ensure 'at' is the correct offset for this key. { if (!*key) { // empty key = only type was given so assign all to structure object // do not assign size here since it will be assigned in StructCreate later mArraySize = aArrsize; mIsPointer = aIspointer; mIsInteger = aIsinteger; mIsUnsigned = aIsunsigned; mEncoding = aEncoding; mVarRef = variableref; return (FieldType*)true; } if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity. || !(key = _tcsdup(key))) // Attempt to duplicate key-string. { // Out of memory. return NULL; } // There is now definitely room in mFields for a new field. FieldType &field = mFields[at]; if (at < mFieldCount) // Move existing fields to make room. memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType)); ++mFieldCount; // Only after memmove above. // Update key-type offsets based on where and what was inserted; also update this key's ref count: field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign(). field.key = key; // Above has already copied string field.mArraySize = aArrsize; field.mIsPointer = aIspointer; field.mOffset = aOffset; field.mIsInteger = aIsinteger; field.mIsUnsigned = aIsunsigned; field.mEncoding = aEncoding; field.mVarRef = variableref; field.mMemAllocated = 0; return &field; } #ifdef CONFIG_DEBUGGER void Struct::DebugWriteProperty(IDebugProperties *aDebugger, int aPage, int aPageSize, int aDepth) { DebugCookie cookie; aDebugger->BeginProperty(NULL, "object", (int)mFieldCount, cookie); if (aDepth) { int i = aPageSize * aPage, j = aPageSize * (aPage + 1); if (j > (int)mFieldCount) j = (int)mFieldCount; // For each field in the requested page... for ( ; i < j; ++i) { Struct::FieldType &field = mFields[i]; ExprTokenType value; TCHAR buf[MAX_PATH]; value.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = this; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; this->Invoke(value,aThisToken,0,&aVarToken,1); delete aVarToken; if (field.mEncoding != 65535) // String aDebugger->WriteProperty(CStringUTF8FromTChar(field.key), value); } } aDebugger->EndProperty(cookie); } #endif
tinku99/ahkdll
9b4bb22ad542a4cf7cac3eff573e434c0ba56de6
Fixed double and float return type in DynaCall + ahk[Post]Function
diff --git a/source/defines.h b/source/defines.h index 4f74f10..01bc906 100644 --- a/source/defines.h +++ b/source/defines.h @@ -133,740 +133,742 @@ enum ToggleValueType {TOGGLE_INVALID = 0, TOGGLED_ON, TOGGLED_OFF, ALWAYS_ON, AL , TOGGLE_PERMIT, 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. // In addition, BIF_InStr relies on SCS_SENSITIVE being 1: enum StringCaseSenseType {SCS_INSENSITIVE, SCS_SENSITIVE, SCS_INSENSITIVE_LOCALE, SCS_INSENSITIVE_LOGICAL, SCS_INVALID}; enum SymbolType // For use with ExpandExpression() and IsPureNumeric(). { // The sPrecedence array in ExpandExpression() must be kept in sync with any additions, removals, // or re-ordering of the below. Also, IS_OPERAND() relies on all operand types being at the // beginning of the list: 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_VAR // An operand that is a variable's contents. , SYM_OPERAND // Generic/undetermined type of operand. , SYM_OBJECT // L31: Represents an IObject interface pointer. , SYM_DYNAMIC // An operand that needs further processing during the evaluation phase. , 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_DOT // DOT must precede SYM_OPAREN so YIELDS_AN_OPERAND(SYM_GET) == TRUE, allowing auto-concat to work for it even though it is positioned after its second operand. , 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_FLOORDIVIDE , SYM_ASSIGN_BITOR, SYM_ASSIGN_BITXOR, SYM_ASSIGN_BITAND, SYM_ASSIGN_BITSHIFTLEFT, SYM_ASSIGN_BITSHIFTRIGHT , 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, SYM_AND // MUST BE KEPT IN THIS ORDER AND ADJACENT TO THE ABOVE because infix-to-postfix is optimized to check a range rather than a series of equalities. , SYM_LOWNOT // LOWNOT is the word "not", the low precedence counterpart of ! , SYM_EQUAL, SYM_EQUALCASE, SYM_NOTEQUAL // =, ==, <> ... Keep this in sync with IS_RELATIONAL_OPERATOR() below. , 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_CONCAT , 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 BIT OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK. , SYM_BITAND , SYM_BITSHIFTLEFT, SYM_BITSHIFTRIGHT // << >> ALSO: SYM_BITSHIFTRIGHT MUST BE KEPT LAST AMONG THE BIT OPERATORS BECAUSE IT'S USED IN A RANGE-CHECK. , SYM_ADD, SYM_SUBTRACT , SYM_MULTIPLY, SYM_DIVIDE, SYM_FLOORDIVIDE , SYM_NEGATIVE, SYM_HIGHNOT, SYM_BITNOT, SYM_ADDRESS, SYM_DEREF // 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. , SYM_POWER // See comments near precedence array for why this takes precedence over SYM_NEGATIVE. , 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. , SYM_FUNC // A call to a function. , SYM_NEW // new Class() , SYM_REGEXMATCH // L31: Experimental ~= RegExMatch operator, equivalent to a RegExMatch call in two-parameter mode. , 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. }; // These two are macros for maintainability (i.e. seeing them together here helps maintain them together). #define SYM_DYNAMIC_IS_DOUBLE_DEREF(token) (token.buf) // SYM_DYNAMICs other than doubles have NULL buf, at least at the stage this macro is called. #define SYM_DYNAMIC_IS_VAR_NORMAL_OR_CLIP(token) (!(token)->buf && ((token)->var->Type() == VAR_NORMAL || (token)->var->Type() == VAR_CLIPBOARD)) // i.e. it's an environment variable or the clipboard, not a built-in variable or double-deref. struct ExprTokenType; // Forward declarations for use below. struct IDebugProperties; struct DECLSPEC_NOVTABLE IObject // L31: Abstract interface for "objects". { // See script_object.cpp for comments. virtual ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount) = 0; // Simple reference-counting mechanism. Usage should be similar to IUnknown (COM). // Some scripts may rely on these being at the same offset as IUnknown::AddRef/Release. virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0; virtual ULONG STDMETHODCALLTYPE Release(void) = 0; #ifdef CONFIG_DEBUGGER virtual void DebugWriteProperty(IDebugProperties *, int aPage, int aPageSize, int aMaxDepth) = 0; #endif }; #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, LPTSTR aValue) = 0; virtual void WriteProperty(LPCSTR aName, __int64 aValue) = 0; virtual void WriteProperty(LPCSTR aName, IObject *aValue) = 0; virtual void WriteProperty(LPCSTR aName, ExprTokenType &aValue) = 0; virtual void WriteProperty(INT_PTR aKey, ExprTokenType &aValue) = 0; virtual void WriteProperty(IObject *aKey, ExprTokenType &aValue) = 0; virtual void BeginProperty(LPCSTR aName, LPCSTR aType, int aNumChildren, DebugCookie &aCookie) = 0; virtual void EndProperty(DebugCookie aCookie) = 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 // L40: MetaObject::Invoke relies on these being mutually-exclusive bits. #define IT_BITMASK 3 // bit-mask for the above. #define IF_METAOBJ 0x10000 // Indicates 'this' is a meta-object/base of aThisToken. Restricts some functionality and causes aThisToken to be inserted into the param list of called functions. #define IF_METAFUNC 0x20000 // Indicates Invoke should call a meta-function before checking the object's fields. #define IF_META (IF_METAOBJ | IF_METAFUNC) // Flags for regular recursion into base object. #define IF_FUNCOBJ 0x40000 // Indicates 'this' is a function, being called via another object (aParam[0]). struct DerefType; // Forward declarations for use below. 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; DerefType *deref; // for SYM_FUNC Var *var; // for SYM_VAR LPTSTR marker; // for SYM_STRING and SYM_OPERAND. }; union // Due to the outermost union, this doesn't increase the total size of the struct on x86 builds (but it does on x64). It's used by SYM_FUNC (helps built-in functions), SYM_DYNAMIC, SYM_OPERAND, and perhaps other misc. purposes. { LPTSTR buf; size_t marker_length; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; }; }; // Note that marker's str-length should not be stored in this struct, even though it might be readily // available in places and thus help performance. This is because if it were stored and the marker // or SYM_VAR's var pointed to a location that was changed as a side effect of an expression's // call to a script function, the length would then be invalid. SymbolType symbol; // Short-circuit benchmark is currently much faster with this and the next beneath the union, perhaps due to CPU optimizations for 8-byte alignment. union { ExprTokenType *circuit_token; // Facilitates short-circuit boolean evaluation. LPTSTR mem_to_free; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; // The above two probably need to be adjacent to each other to conserve memory due to 8-byte alignment, // which is the default alignment (for performance reasons) in any struct that contains 8-byte members // such as double and __int64. }; #define MAX_TOKENS 512 // Max number of operators/operands. Seems enough to handle anything realistic, while conserving call-stack space. #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. // 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_ASSIGN, ACT_ASSIGNEXPR, ACT_EXPRESSION, ACT_ADD, ACT_SUB, ACT_MULT, ACT_DIV , ACT_ASSIGN_FIRST = ACT_ASSIGN, ACT_ASSIGN_LAST = ACT_DIV , ACT_REPEAT // Never parsed directly, only provided as a translation target for the old command (see other notes). , ACT_ELSE // Parsed at a lower level than most commands to support same-line ELSE-actions (e.g. "else if"). , ACT_IFIN, ACT_IFNOTIN, ACT_IFCONTAINS, ACT_IFNOTCONTAINS, ACT_IFIS, ACT_IFISNOT , ACT_IFBETWEEN, ACT_IFNOTBETWEEN , ACT_IFEXPR // i.e. if (expr) // *** *** *** KEEP ALL OLD-STYLE/AUTOIT V2 IFs AFTER THIS (v1.0.20 bug fix). *** *** *** , ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // ACT_IS_IF_OLD() relies upon ACT_IFEQUAL through ACT_IFLESSOREQUAL being adjacent to one another // and it relies upon the fact that ACT_IFEQUAL is first in the series and ACT_IFLESSOREQUAL last. , ACT_IFEQUAL = ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION, ACT_IFNOTEQUAL, ACT_IFGREATER, ACT_IFGREATEROREQUAL , ACT_IFLESS, ACT_IFLESSOREQUAL , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes. , ACT_IFWINEXIST = ACT_FIRST_COMMAND , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE , ACT_IFINSTRING, ACT_IFNOTINSTRING , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX // Keep this range updated with any new IFs that are added. , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE , ACT_GETKEYSTATE , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS , ACT_STATUSBARGETTEXT , ACT_STATUSBARWAIT , ACT_CLIPWAIT, ACT_KEYWAIT , ACT_SLEEP, ACT_RANDOM , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_CONTINUE // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_TRY, ACT_CATCH, ACT_THROW , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE , ACT_WINHIDE, ACT_WINSHOW , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE // Keep rarely used actions near the bottom for parsing/performance reasons: , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME , ACT_FILEGETSIZE, ACT_FILEGETVERSION , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_SETREGVIEW , ACT_OUTPUTDEBUG , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME , ACT_SUSPEND, ACT_PAUSE , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET , ACT_EXITAPP , ACT_SHUTDOWN , ACT_FILEENCODING // Make these the last ones before the count so they will be less often processed. This helps // performance because this one doesn't actually have a keyword so will never result // in a match anyway. UPDATE: No longer used because Run/RunWait is now required, which greatly // improves syntax checking during load: //, ACT_EXEC // It's safer to use g_ActionCount, which is calculated immediately after the array is declared // and initialized, at which time we know its true size. However, the following lets us detect // when the size of the array doesn't match the enum (in debug mode): #ifdef _DEBUG , ACT_COUNT #endif }; enum enum_act_old { OLD_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order: , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL , OLD_LEFTCLICK, OLD_RIGHTCLICK, OLD_LEFTCLICKDRAG, OLD_RIGHTCLICKDRAG , OLD_HIDEAUTOITWIN, OLD_REPEAT, OLD_ENDREPEAT , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS }; // It seems best not to include ACT_SUSPEND in the below, since the user may have marked // a large number of subroutines as "Suspend, Permit". Even PAUSE is iffy, since the user // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey // was 1 (the default). #ifndef MINIDLL #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \ || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS) #else #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_RELOAD) #endif #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance. #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF) #define ACT_IS_IF_OR_ELSE_OR_LOOP(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ActionType == ACT_LOOP || ActionType == ACT_WHILE || ActionType == ACT_FOR) #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \ && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL)) // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new") // can support parameters on the same line or on the next line. For example, both of the above are allowed: // IfMsgBox, No, Gosub, XXX // IfMsgBox, No // Gosub, XXX // 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 // 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. #ifndef MINIDLL #define MAX_INPUTBOXES 4 #define MAX_PROGRESS_WINDOWS 10 // Allow a lot for downloads and such. #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above. #define MAX_SPLASHIMAGE_WINDOWS 10 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above. #endif #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. #ifndef MINIDLL #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #endif #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. #ifndef MINIDLL #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #endif #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. #ifndef MINIDLL // 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 #endif #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 CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close() #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; // Just make them int's, rather than something smaller, because the collection // of actions will take up very little memory. Int's are probably faster // for the processor to access since they are the native word size, or something: // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform() // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for // non-AutoIt2 scripts, such as the extra ones in StringGetPos). // Also, changing these from ints to chars greatly reduces 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, MaxParamsAu2WithHighBit; // Array indicating which args must be purely numeric. The first arg is // number 1, the second 2, etc (i.e. it doesn't start at zero). The list // is ended with a zero, much like a string. The compiler will notify us // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased: #define MAX_NUMERIC_PARAMS 7 ActionTypeType NumericParams[MAX_NUMERIC_PARAMS]; }; #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}; #ifndef MINIDLL 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("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")} enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely). , GUI_EVENT_RCLK, GUI_EVENT_COLCLK , GUI_EVENT_FIRST_UNNAMED // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below. , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield). #endif typedef USHORT CoordModeType; // Bit-field offsets: #ifndef MINIDLL #define COORD_MODE_PIXEL 0 #endif #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #ifndef MINIDLL #define COORD_MODE_MENU 8 #endif #define COORD_MODE_WINDOW 0 #define COORD_MODE_CLIENT 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #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; } // Same reason as above struct. It's best to keep this struct as small as possible // because it's used as a local (stack) var by at least one recursive function: // Each instance of this struct generally corresponds to a quasi-thread. The function that creates // a new thread typically saves the old thread's struct values on its stack so that they can later // be copied back into the g struct when the thread is resumed: class Func; // Forward declarations struct FuncAndToken { ExprTokenType mToken ; LPTSTR result_to_return_dll; Func * mFunc ; VARIANT variant_to_return_dll; + LPTSTR param[10]; + BYTE mParamCount; }; class Label; // class Line; // struct RegItemStruct; // struct LoopReadFileStruct; // #ifndef MINIDLL class GuiType; // #endif struct global_struct { // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious). __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values. __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. WIN32_FIND_DATA *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. // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class // because they're more appropriate as thread-attributes rather than being global to the entire script. TitleMatchModes TitleMatchMode; int IntervalBeforeRest; int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible. int Priority; // This thread's priority relative to others. DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. #ifndef MINIDLL GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click. #endif EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard. #ifndef MINIDLL POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed. GuiType *GuiWindow; // The GUI window that launched this thread. GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..." GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid. GuiType *DialogOwner; // This thread's GUI owner, if any. GuiIndexType GuiControlIndex; // The GUI control index that launched this thread. #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL) #endif 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; // TCHAR FormatFloat[32]; Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine. Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. //HWND hWndToRestore; int MsgBoxResult; // Which button was pressed in the most recent MsgBox. HWND DialogHWND; DWORD RegView; // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: SendModes SendMode; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. DWORD ThreadStartTime; int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too). bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness. 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 AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. 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; CoordModeType CoordMode; // Bitwise collection of flags. UCHAR StringCaseSense; // On/Off/Locale bool StoreCapslockMode; bool AutoTrim; char FormatInt; SendLevelType SendLevel; bool MsgBoxTimedOut; // Doesn't require initialization. bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle". bool ListLinesIsEnabled; UINT Encoding; ExprTokenType* ThrownToken; Line* ExcptLine; bool InTryBlock; }; inline void global_maximize_interruptibility(global_struct &g) { g.AllowThreadToBeInterrupted = true; g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.ThreadIsCritical = false; g.AllowTimers = true; #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. } inline void global_clear_state(global_struct &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 ErrorLevel shouldn't). { g.CurrentFunc = NULL; g.CurrentFuncGosub = NULL; g.CurrentLabel = NULL; g.hWndLastUsed = NULL; //g.hWndToRestore = NULL; g.MsgBoxResult = 0; g.IsPaused = false; g.UninterruptedLineCount = 0; #ifndef MINIDLL g.DialogOwner = NULL; #endif g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true. #ifndef MINIDLL g.GuiDefaultWindow = NULL; #endif // Above line is done because allowing it to be permanently changed by the auto-exec section // seems like it would cause more confusion that it's worth. A change to the global default // or even an override/always-use-this-window-number mode can be added if there is ever a // demand for it. 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.InTryBlock = false; } inline void global_init(global_struct &g) // This isn't made a real constructor to avoid the overhead, since there are times when we // want to declare a local var of type global_struct without having it initialized. { // 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: global_clear_state(g); g.SendMode = SM_INPUT_FALLBACK_TO_PLAY; // v1.1.7.3: Default to SM_INPUT_FALLBACK_TO_PLAY for best performance. g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3. 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. // Not sure what the optimal default is. 1 seems too low (scripts would be very slow by default): g.LinesPerCycle = -1; g.IntervalBeforeRest = 10; // sleep for 10ms every 10ms #define DEFAULT_PEEK_FREQUENCY 5 g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL. g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values. g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.AllowTimers = true; g.ThreadIsCritical = false; g.Priority = 0; g.LastError = 0; #ifndef MINIDLL g.GuiEvent = GUI_EVENT_NONE; #endif g.EventInfo = NO_EVENT_INFO; #ifndef MINIDLL g.GuiPoint.x = COORD_UNSPECIFIED; g.GuiPoint.y = COORD_UNSPECIFIED; // For these, indexes rather than pointers are stored because handles can become invalid during the // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself): g.GuiWindow = NULL; g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds. g.GuiDefaultWindow = NULL; #endif 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.StringCaseSense = SCS_INSENSITIVE; // AutoIt2 default, and it does seem best. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.AutoTrim = true; // AutoIt2's default, and overall the best default in most cases. _tcscpy(g.FormatFloat, _T("%0.6f")); g.FormatInt = 'D'; g.SendLevel = 0; g.ListLinesIsEnabled = true; g.Encoding = CP_ACP; // For FormatFloat: // I considered storing more than 6 digits to the right of the decimal point (which is the default // for most Unices and MSVC++ it seems). But going beyond that makes things a little weird for many // numbers, due to the inherent imprecision of floating point storage. For example, 83648.4 divided // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with // 20 digits. The extra zeros could be chopped off the end easily enough, but even so, going beyond // 6 digits seems to do more harm than good for the avg. user, overall. A default of 6 is used here // in case other/future compilers have a different default (for backward compatibility, we want // 6 to always be in effect as the default for future releases). } #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel. #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) // 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 diff --git a/source/exports.cpp b/source/exports.cpp index 1cd65d0..a8784d7 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,735 +1,750 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(int timeout){return ahkTerminate(timeout);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(int timeout){return ahkReload(timeout);} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; - for (int i=0;i<10;i++) + for (int i=0;i < aParamsCount;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount = i + 1; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); - aParam[aParamCount]->symbol = SYM_STRING;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters + aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); return 0; } else { - for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) - aFunc->mParam[aParamCount].var->Assign(*params[aParamCount]); + FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; + aFuncAndToken.mParamCount = aParamsCount; + for (int i = 0;i < 10;i++) + { + aFuncAndToken.param[aParamCount] = (LPTSTR)realloc(aFuncAndToken.param[aParamCount],_tcslen(*params[aParamCount])*sizeof(WCHAR)); + _tcscpy(aFuncAndToken.param[aParamCount],*params[aParamCount]); + } + //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) + // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } } else // Function not found return -1; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mStaticVar, func.mStaticVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); g_script.PreprocessLocalVars(func, func.mStaticLazyVar, func.mStaticLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { int aParamCount = 0; int aParamsCount = 0; LPTSTR *params[10]; params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; for (int i=0;i<10;i++) { if (*params[i] && _tcscmp(*params[i],_T(""))) aParamsCount = i + 1; } if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); - aParam[aParamCount]->symbol = SYM_STRING;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters + aParam[aParamCount]->symbol = SYM_OPERAND;aParam[aParamCount]->marker = *params[aParamCount]; // Assign parameters } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); switch (aResultToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aResultToken.var->Contents())) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.var->Contents())*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aResultToken.marker)) { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.marker)*sizeof(TCHAR)); _tcscpy(result_to_return_dll,aResultToken.marker); } else if (result_to_return_dll) *result_to_return_dll = '\0'; break; case SYM_INTEGER: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aResultToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aResultToken.value_int64, result_to_return_dll); } return result_to_return_dll; } else // UDF { - for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) - aFunc->mParam[aParamCount].var->Assign(*params[aParamCount]); + //for (;aFunc->mParamCount > aParamCount && aParamsCount>aParamCount;aParamCount++) + // aFunc->mParam[aParamCount].var->AssignString(*params[aParamCount]); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; + aFuncAndToken.mParamCount = aParamsCount; + for (int i = 0;i < aParamsCount;i++) + { + aFuncAndToken.param[aParamCount] = (LPTSTR)realloc(aFuncAndToken.param[aParamCount],_tcslen(*params[aParamCount])*sizeof(WCHAR)); + _tcscpy(aFuncAndToken.param[aParamCount],*params[aParamCount]); + } aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } } else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); + for (int aParamCount = 0;func.mParamCount > aParamCount && aFuncAndToken->mParamCount > aParamCount;aParamCount++) + func.mParam[aParamCount].var->AssignString(aFuncAndToken->param[aParamCount]); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { VARIANT *variants[10]; int aParamCount = 0; variants[0]=&param1;variants[1]=&param2;variants[2]=&param3;variants[3]=&param4;variants[4]=&param5; variants[5]=&param6;variants[6]=&param7;variants[7]=&param8;variants[8]=&param9;variants[9]=&param10; if(aFunc->mIsBuiltIn) { ResultType aResult = OK; ExprTokenType aResultToken; ExprTokenType **aParam = (ExprTokenType**)_alloca(sizeof(ExprTokenType)*10); for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) { aParam[aParamCount] = (ExprTokenType*)_alloca(sizeof(ExprTokenType)); aParam[aParamCount]->symbol = SYM_VAR; aParam[aParamCount]->var = (Var*)alloca(sizeof(Var)); // prepare variable aParam[aParamCount]->var->mType = VAR_NORMAL; aParam[aParamCount]->var->mAttrib = 0; aParam[aParamCount]->var->mByteCapacity = 0; aParam[aParamCount]->var->mHowAllocated = ALLOC_MALLOC; AssignVariant(*aParam[aParamCount]->var, *variants[aParamCount],false); } aResultToken.symbol = SYM_INTEGER; aResultToken.marker = aFunc->mName; aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); // free all variables in case memory was allocated for (;aParamCount >= 0;aParamCount--) aParam[aParamCount]->var->Free(); TokenToVariant(aResultToken, variant_to_return_dll); return variant_to_return_dll; } else // UDF { for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) AssignVariant(*aFunc->mParam[aParamCount].var, *variants[aParamCount],false); FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/script2.cpp b/source/script2.cpp index 620a315..4f94e8a 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -12387,1128 +12387,1137 @@ DYNARESULT DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD & cp = (BYTE *)&this_param.value_int + param_size - 4; // Start at the right side of the arg and work leftward. while (param_size > 0) { stack_dword = *(DWORD *)cp; // Get first four bytes cp -= 4; // Next part of argument --our_stack; // ESP = ESP - 4 *our_stack = stack_dword; // SS:[ESP] = stack_dword param_size -= 4; } } } if ((aRet != NULL) && ((aFlags & DC_BORLAND) || (aRetSize > 8))) { // Return value isn't passed through registers, memory copy // is performed instead. Pass the pointer as hidden arg. our_stack_size += 4; // Add stack size --our_stack; // ESP = ESP - 4 *our_stack = (DWORD)(size_t)aRet; // 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 { add esp, reserved_stack_size // Restore to original position mov esp_start, esp // For detecting whether a DC_CALL_STD function was sent too many or too few args. sub esp, our_stack_size // 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 dwEAX, eax // Save eax/edx registers mov dwEDX, edx } // 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] else if (!aRet) { _asm { mov eax, [dwEAX] mov DWORD PTR [Res], eax mov edx, [dwEDX] mov DWORD PTR [Res + 4], edx } } else if (((aFlags & DC_BORLAND) == 0) && (aRetSize <= 8)) { // Microsoft optimized less than 8-bytes structure passing _asm { mov ecx, DWORD PTR [aRet] mov eax, [dwEAX] mov DWORD PTR [ecx], eax mov edx, [dwEDX] mov DWORD PTR [ecx + 4], edx } } #endif // WIN32_PLATFORM #ifdef _WIN64 int params_left = aParamCount; DWORD_PTR regArgs[4]; DWORD_PTR* stackArgs = NULL; size_t stackArgsSize = 0; // The first four parameters are passed in x64 through registers... like ARM :D for(int i = 0; (i < 4) && params_left; i++, params_left--) regArgs[i] = 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 // 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. if (esp_delta && (aFlags & DC_CALL_STD)) { *buf = 'A'; // The 'A' prefix indicates the call was made, but with too many or too few args. _itot(esp_delta, buf + 1, 10); g_script.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Assign buf not _itot()'s return value, which is the wrong location. } 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.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Positive ErrorLevel numbers are reserved for exception codes. } else g_ErrorLevel->Assign(ERRORLEVEL_NONE); return Res; } void ConvertDllArgType(LPTSTR aBuf[], DYNAPARM &aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[32]; int i; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf[0]; i < 2 && type_string; type_string = aBuf[++i]) { 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) { // The following also serves to set the default in case this is the first iteration. // Set default but perform second iteration in case the second type string isn't NULL. // In other words, if the second type string is explicitly valid rather than blank, // it should override the following default: aDynaParam.type = DLL_ARG_INVALID; // To assist with detection of errors like DllCall(...,flaot,n), treat empty string as an error; naked "CDecl" is now handled elsewhere. OBSOLETE COMMENT: Assume int. This is relied upon at least for having a return type such as a naked "CDecl". continue; // OK to do this regardless of whether this is the first or second iteration. } tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below. // v1.0.30.02: The addition of 'P' allows the quotes to be omitted around a pointer type. // However, the current detection below relies upon the fact that not 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; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsicmp(buf, _T(t))) aDynaParam.type = (n); TEST_TYPE("Int", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("Str", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("Ptr", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("Ptr", DLL_ARG_INT) #endif TEST_TYPE("Short", DLL_ARG_SHORT) TEST_TYPE("Char", DLL_ARG_CHAR) TEST_TYPE("Int64", DLL_ARG_INT64) TEST_TYPE("Float", DLL_ARG_FLOAT) TEST_TYPE("Double", DLL_ARG_DOUBLE) TEST_TYPE("AStr", DLL_ARG_ASTR) TEST_TYPE("WStr", DLL_ARG_WSTR) TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. { if (i > 0) // Second iteration. { // Reset flags to go with any blank value (i.e. !*buf) we're falling back to from the first iteration // (in case our iteration changed the flags based on bogus contents of the second type_string): aDynaParam.passed_by_address = false; aDynaParam.is_unsigned = false; //aDynaParam.type: The first iteration already set it to DLL_ARG_INT or DLL_ARG_INVALID. } else // First iteration, so aDynaParam.type's value will be set by the second (however, the loop's own condition will skip the second iteration if the second type_string is NULL). { aDynaParam.type = DLL_ARG_INVALID; // Set in case of: 1) the second iteration is skipped by the loop's own condition (since the caller doesn't always initialize "type"); or 2) the second iteration can't find a valid type. continue; } } // Since above didn't "continue", the type is explicitly valid so "return" to ensure that // the second iteration doesn't run (in case this is the first iteration): return; } } int ConvertDllArgTypes(LPTSTR aBuf, DYNAPARM *aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[1024]; int i; int arg_count = 0; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf; *type_string; type_string = (aBuf + (++i))) { if (_tcschr(type_string,'=') || ctoupper(*type_string) == 'U' || (*type_string == '*') )// Unsigned continue; if (i>0 && ctoupper(*(aBuf + i - 1)) == 'U') // Unsigned aDynaParam[arg_count].is_unsigned = true; else aDynaParam[arg_count].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) break; tcslcpy(buf, type_string+1, 2); // Make a modifiable copy for easier parsing below. if (StrChrAny(buf, _T("*pP"))) // Additional validation: ensure nothing following the suffix. aDynaParam[arg_count].passed_by_address = true; else aDynaParam[arg_count].passed_by_address = false; tcslcpy(buf, type_string, 2); // Make a modifiable copy for easier parsing below. if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(buf, _T(t), 1)) aDynaParam[arg_count].type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. break; arg_count++; } return arg_count; } bool IsDllArgTypeName(LPTSTR name) // Test whether given name is a valid DllCall arg type (used by Script::MaybeWarnLocalSameAsGlobal). { LPTSTR names[] = { name, NULL }; DYNAPARM param; // An alternate method using an array of strings and tcslicmp in a loop benchmarked // slightly faster than this, but didn't seem worth the extra code size. This should // be more maintainable and is guaranteed to be consistent with what DllCall accepts. ConvertDllArgType(names, param); return param.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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } BIF_DECL(BIF_DynaCall) { IObject *obj = NULL; if (aParam[0]->symbol == SYM_OBJECT) { aParam[0]->object->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); } else if (aParamCount == 1 && aParam[0]->symbol == PURE_INTEGER) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // DynaToken *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; DYNAPARM *dyna_param; ExprTokenType token; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. + //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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (aParamCount > 1) { if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } else if (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject()) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string[1]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE,TRUE); } else { return_type_string[0] = token.marker; } int i = 0; for (;return_type_string[0][i];i++) { if ( !(_tcschr(return_type_string[0]+i,'=') || ctoupper(return_type_string[0][i]) == 'U' || ctoupper(return_type_string[0][i]) == 'P' || (return_type_string[0][i] == '*')) )// Unsigned obj->marg_count++; } dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string[0],dyna_param)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string[0],'=')) { #ifdef WIN32_PLATFORM if (_tcschr((_tcschr(return_type_string[0],'=') + 1),'=')) obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR retrurn_type_arg[3]; // maximal length of return type for (i=0;_tcschr(return_type_string[0] + i + 1,'=');i++) retrurn_type_arg[i] = return_type_string[0][i]; retrurn_type_arg[i] = '\0'; if (StrChrAny(retrurn_type_arg, _T("uU"))) { _tcsncpy(retrurn_type_arg,retrurn_type_arg + 1,sizeof(TCHAR)); _tcsncpy(retrurn_type_arg + 1,retrurn_type_arg + 2,sizeof(TCHAR)); //*(retrurn_type_arg + 2) = '\0'; obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(retrurn_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(retrurn_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } +#ifdef WIN32_PLATFORM + if (!obj->mreturn_attrib.passed_by_address) // i.e. the special return flags below are not needed when an address is being returned. + { + if (obj->mreturn_attrib.type == DLL_ARG_DOUBLE) + obj->mdll_call_mode |= DC_RETVAL_MATH8; + else if (obj->mreturn_attrib.type == DLL_ARG_FLOAT) + obj->mdll_call_mode |= DC_RETVAL_MATH4; + } +#endif } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); if (!obj->mfunction) { g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DynaCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } // allocate memory for parameters and default parameters // in current design we need to have mdefault_param to be initialized // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); int i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before passing a buffer 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 (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParamCount > 1 && aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters IObject *paramobj = ((aParam[1]->symbol == SYM_OBJECT) ? aParam[1]->object : aParam[1]->var->mObject); oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); paramobj->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. if (result_token.value_int64 < 2) { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } else { obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; paramobj->Invoke(result_token,*aParam[1],IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } else { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; if (is_call && aParam[0]->symbol == SYM_OPERAND && _tcscmp(aParam[0]->marker,_T(""))) { ConvertDllArgType(&aParam[0]->marker, return_attrib); } // Set default dynacall parameters for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) break; ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DynaCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DynaCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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.
tinku99/ahkdll
b7d2602dabee97e176b8ad9660e20d79a9caa1c7
Fixed string termination
diff --git a/source/script_struct.cpp b/source/script_struct.cpp index 401085d..53ec009 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -986,922 +986,922 @@ ResultType STDMETHODCALLTYPE Struct::Invoke( } } } else if (!IS_INVOKE_CALL) // IS_INVOKE_CALL will handle the field itself field = FindField(TokenToString(*aParam[0])); } // // OPERATE ON A FIELD WITHIN THIS OBJECT // // CALL if (IS_INVOKE_CALL) { LPTSTR name = TokenToString(*aParam[0]); if (*name == '_') ++name; // ++ to exclude '_' from further consideration. ++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case. if (!_tcsicmp(name, _T("NewEnum"))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return _NewEnum(aResultToken, aParam, aParamCount); } // if first function parameter is a field get it if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0])) { if (field = FindField(TokenToString(*aParam[0]))) { // exclude parameter in aParam ++aParam; --aParamCount; } } aResultToken.symbol = SYM_INTEGER; // mostly used aResultToken.value_int64 = 0; // set default if (!_tcsicmp(name, _T("SetCapacity"))) { // Set strcuture its capacity or fields capacity if (!field) { if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { // 0 or no parameters were given to free memory if (mMemAllocated > 0) { mMemAllocated = 0; free(mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mMemAllocated > 0) free(mStructMem); // allocate memory and zero-fill if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(mStructMem,NULL,(size_t)mMemAllocated); aResultToken.value_int64 = mMemAllocated; } else mMemAllocated = 0; } else if (aParamCount) { // we must have to parmeters here since first parameter is field if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { if (field->mMemAllocated > 0) { field->mMemAllocated = 0; free(field->mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // not numeric } if (field->mMemAllocated > 0) free(field->mStructMem); // allocate memory and zero-fill if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { field->mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(field->mStructMem,NULL,(size_t)field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; aResultToken.value_int64 = mMemAllocated; } else field->mMemAllocated = 0; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetCapacity"))) { if (field) aResultToken.value_int64 = field->mMemAllocated; else aResultToken.value_int64 = mMemAllocated; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Offset"))) { if (field) aResultToken.value_int64 = field->mOffset; else if (aParamCount && TokenIsPureNumeric(*aParam[0])) // calculate size if item is an array aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("IsPointer"))) { if (field) aResultToken.value_int64 = field->mIsPointer; else aResultToken.value_int64 = mIsPointer; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Encoding"))) { if (field) aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding; else aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetPointer"))) { if (!field && aParamCount && mIsPointer) { // resolve array item if (mArraySize && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1)))); else aResultToken.value_int64 = *target; } else if (field) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset)); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Fill"))) { if (!field) // only allow to fill main structure { if (aParamCount && TokenIsPureNumeric(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize); else if (aParamCount && *TokenToString(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize); else memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetAddress"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1)); else aResultToken.value_int64 = (UINT_PTR)target; } else aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Size"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) // we do not care which item was requested because all are same size aResultToken.value_int64 = mSize / mArraySize; else aResultToken.value_int64 = mSize; } else aResultToken.value_int64 = field->mSize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("CountOf"))) { if (!field) aResultToken.value_int64 = mArraySize; else aResultToken.value_int64 = field->mArraySize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New"))) { if (!field) { if (!releaseobj) // else we have a clone already objclone = this->Clone(); } else { Struct* tempobj = objclone; if (releaseobj) // release object, it is not requred anymore { objclone = objclone->CloneField(field); tempobj->Release(); } else objclone = this->CloneField(field); } if (aParamCount) { // structure pointer and / or init object were given if (TokenIsPureNumeric(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]); objclone->mMemAllocated = 0; if (aParamCount > 1 && TokenToObject(*aParam[1])) objclone->ObjectToStruct(TokenToObject(*aParam[1])); } else if (TokenToObject(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); objclone->ObjectToStruct(TokenToObject(*aParam[0])); } } else { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); } // small fix for _New to work properly because aThisToken contains the new object if (!_tcsicmp(name, _T("_New"))) { if (aThisToken.symbol == SYM_OBJECT) aThisToken.object->Release(); else aThisToken.symbol = SYM_OBJECT; aThisToken.object = objclone; objclone->AddRef(); } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; if (deletefield) // we created the field from a structure delete field; // do not release objclone because it is returned return OK; } // For maintainability: explicitly return since above has done ++aParam, --aParamCount. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // identify that method was not found return INVOKE_NOT_HANDLED; } else if (!field) { // field was not found if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x]. else if (param_count_excluding_rvalue > 1) { // second parameter = "", so caller wants get/set field pointer if (TokenIsEmptyString(*aParam[1])) { aResultToken.symbol = SYM_INTEGER; if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) { // set simple pointer *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]); aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset); } else // set pointer to pointer { UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset; else { // get pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // clone field to object and invoke again { if (releaseobj) objclone->Release(); objclone = CloneField(field,true); /* if (!field->mArraySize && field->mIsPointer) { objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); //objclone->mIsPointer--; if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array objclone->mArraySize = 1; } else objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize)); */ objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); if (deletefield) // we created the field from a structure delete field; return OK; } } // MULTIPARAM[x,y] x[y] // SET else if (IS_INVOKE_SET) { if (field->mVarRef && TokenToObject(*aParam[1])) { // field is a structure, assign objct to structure if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer, clone to structure and invoke again if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); objclone->Release(); return OK; } // StrPut (code stolen from BIF_StrPut()) if (field->mEncoding != 65535) { // field is [T|W|U]CHAR or LP[TC]STR, set get character or string source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf); source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string)); //if (field->mSize > 2) // not [T|W|U]CHAR // source_length++; // for terminating character if (!source_length) { // Take a shortcut when source_string is empty, since some paths below might not handle it correctly. if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return { aResultToken.value_int64 = 0; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mEncoding == CP_UTF16) *(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; else *(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; aResultToken.value_int64 = 1; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } if (field->mSize > 2 && (!*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated < ((source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR))))))) { // no memory allocated yet, allocate now if (field->mMemAllocated == -1 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))){ if (deletefield) // we created the field from a structure so no memory can be allocated delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } else if (field->mMemAllocated > 0) // free previously allocated memory free(field->mStructMem); field->mMemAllocated = (source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)); // + 1 for terminating character field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; } if (field->mEncoding == UorA(CP_UTF16, CP_ACP)) tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length); else { // Conversion is required. For Unicode builds, this means encoding != CP_UTF16; #ifndef UNICODE // therefore, this section is relevant only to ANSI builds: if (field->mEncoding == CP_UTF16) { // See similar section below for comments. char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0); if (!char_count) { aResultToken.value_int64 = char_count; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). length = char_count; char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length); if (field->mSize > 2 && char_count && char_count < length) ((LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)))[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 char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (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(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); } if (!char_count) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). // Assume there is sufficient buffer space and hope for the best: length = char_count; // Convert to target encoding. char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, 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 (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR - ((LPSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0'; + ((LPTSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0'; #ifndef UNICODE } #endif } aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = char_count; } else { switch(field->mSize) { case 4: // Listed first for performance. if (field->mIsInteger) *((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]); else // Float (32-bit). *((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]); break; case 8: if (field->mIsInteger) // v1.0.48: Support unsigned 64-bit integers like DllCall does: *((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values. ? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall(). : TokenToInt64(*aParam[1]); else // Double (64-bit). *((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]); break; case 2: *((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]); break; default: // size 1 *((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]); } //*((int*)target + field->mOffset) = (int)TokenToInt64(*aParam[1]); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TokenToInt64(*aParam[1]); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } // GET else if (field) { if (field->mArraySize || field->mVarRef) { // filed is an array or variable reference, return a structure object. if (field->mArraySize || field->mIsPointer) { // field is array or a pointer to variable objclone = CloneField(field,true); objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } else // field is refference to a variable and not pointer, create structure { Var1.symbol = SYM_STRING; Var2.symbol = SYM_VAR; Var2.var = field->mVarRef; if (TokenToObject(Var2)) { // Variable is a structure object objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target + field->mOffset; aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; } else // Variable is a string definition { Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset); if (objclone = Struct::Create(param,2)) { // create and clone object because it is created dynamically Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; tempobj->Release(); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer of main structure for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer we need to return an object if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // StrGet (code stolen from BIF_StrGet()) if (field->mEncoding != 65535) { if (field->mEncoding != UorA(CP_UTF16, CP_ACP)) { // Conversion is required. int conv_length; if (field->mSize < 4) // TCHAR or CHAR or WCHAR length = 1; #ifdef UNICODE // Convert multi-byte encoded string to UTF-16. conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length); #else CStringW wide_buf; // If the target string is not UTF-16, convert it to that first. if (field->mEncoding != CP_UTF16) { StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding); (field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString(); length = wide_buf.GetLength(); } // Now convert UTF-16 to ACP. conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // Out of memory. } conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL); #endif if (conv_length && !aResultToken.marker[conv_length - 1]) --conv_length; // Exclude null-terminator. else aResultToken.marker[conv_length] = '\0'; aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // no conversation required { if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } aResultToken.symbol = SYM_STRING; if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1)) aResultToken.marker = _T(""); } aResultToken.symbol = SYM_STRING; } else // NumGet (code stolen from BIF_NumGet()) { switch(field->mSize) { case 4: // Listed first for performance. if (!field->mIsInteger) aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset)); else if (!field->mIsUnsigned) aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above. else aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset)); break; case 8: // The below correctly copies both DOUBLE and INT64 into the union. // Unsigned 64-bit integers aren't supported because variables/expressions can't support them. aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset)); break; case 2: if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset)); break; default: // size 1 if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset)); } aResultToken.symbol = SYM_INTEGER; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // // Struct:: Internal Methods // Struct::FieldType *Struct::FindField(LPTSTR val) { for (int i = 0;i < mFieldCount;i++) { FieldType &field = mFields[i]; if (!_tcsicmp(field.key,val)) return &field; } return NULL; } bool Struct::SetInternalCapacity(IndexType new_capacity) // Expands mFields to the specified number if fields. // Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount. { FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType)); if (!new_fields) return false; mFields = new_fields; mFieldCountMax = new_capacity; return true; } ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { if (aParamCount == 0) { IObject *newenum; if (newenum = new Enumerator(this)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = newenum; } } return OK; } int Struct::Enumerator::Next(Var *aKey, Var *aVal) { if (++mOffset < mObject->mFieldCount) { FieldType &field = mObject->mFields[mOffset]; if (aKey) aKey->Assign(field.key); if (aVal) { // We need to invoke the structure to retrieve the value ExprTokenType aResultToken; // not sure about the buffer TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } else if (mOffset < mObject->mArraySize) { // structure is an array if (aKey) aKey->Assign(mOffset + 1); // mOffset starts at 1 if (aVal) { // again we need to invoke structure to retrieve the value ExprTokenType aResultToken; TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_INTEGER; aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1 mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } return false; } Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding) // Inserts a single field with the given key at the given offset. // Caller must ensure 'at' is the correct offset for this key. { if (!*key) { // empty key = only type was given so assign all to structure object // do not assign size here since it will be assigned in StructCreate later mArraySize = aArrsize; mIsPointer = aIspointer; mIsInteger = aIsinteger; mIsUnsigned = aIsunsigned; mEncoding = aEncoding; mVarRef = variableref; return (FieldType*)true; } if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity. || !(key = _tcsdup(key))) // Attempt to duplicate key-string. { // Out of memory. return NULL; } // There is now definitely room in mFields for a new field. FieldType &field = mFields[at]; if (at < mFieldCount) // Move existing fields to make room. memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType)); ++mFieldCount; // Only after memmove above. // Update key-type offsets based on where and what was inserted; also update this key's ref count: field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign(). field.key = key; // Above has already copied string field.mArraySize = aArrsize; field.mIsPointer = aIspointer; field.mOffset = aOffset; field.mIsInteger = aIsinteger; field.mIsUnsigned = aIsunsigned; field.mEncoding = aEncoding; field.mVarRef = variableref; field.mMemAllocated = 0; return &field; } #ifdef CONFIG_DEBUGGER void Struct::DebugWriteProperty(IDebugProperties *aDebugger, int aPage, int aPageSize, int aDepth) { DebugCookie cookie; aDebugger->BeginProperty(NULL, "object", (int)mFieldCount, cookie); if (aDepth) { int i = aPageSize * aPage, j = aPageSize * (aPage + 1); if (j > (int)mFieldCount) j = (int)mFieldCount; // For each field in the requested page... for ( ; i < j; ++i) { Struct::FieldType &field = mFields[i]; ExprTokenType value; TCHAR buf[MAX_PATH]; value.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = this; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; this->Invoke(value,aThisToken,0,&aVarToken,1); delete aVarToken; if (field.mEncoding != 65535) // String aDebugger->WriteProperty(CStringUTF8FromTChar(field.key), value); } } aDebugger->EndProperty(cookie); } #endif
tinku99/ahkdll
e9d18c3da369728f8f3fc8341bb2b0007a626bf5
Fix automatic string memory allocation
diff --git a/source/script_struct.cpp b/source/script_struct.cpp index 8459019..401085d 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -884,1024 +884,1024 @@ ResultType STDMETHODCALLTYPE Struct::Invoke( objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; return OK; } else return INVOKE_NOT_HANDLED; } } else { objclone = Clone(true); releaseobj = true; objclone->mStructMem = target; if (!mArraySize && mIsPointer) objclone->mIsPointer--; else if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } if (objclone->mIsPointer || (aParamCount == 1 && !mTypeOnly)) { if (param_count_excluding_rvalue > 1) { // MULTIPARAM objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } else if (!mTypeOnly) { // the given integer is now excluded from parameters aParamCount--;param_count_excluding_rvalue--;aParam++; } } } if (mTypeOnly && !IS_INVOKE_CALL) // IS_INVOKE_CALL does not need the tentative field, it will handle it itself { if (mVarRef && !TokenIsEmptyString(*aParam[0])) { if (releaseobj) objclone->Release(); Var2.symbol = SYM_VAR; Var2.var = mVarRef; if (TokenToObject(Var2) && (objclone = ((Struct *)TokenToObject(Var2))->Clone(true))) { // variable is a structure object objclone->mStructMem = target; objclone->Invoke(aResultToken,ResultToken ,aFlags,aParam,aParamCount); objclone->Release(); return OK; } else { Var1.symbol = SYM_STRING; Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = 0; if (objclone = Struct::Create(param,2)) { // create structure from variable Struct* tempobj = objclone->Clone(true); // resolve pointer tempobj->mStructMem = mIsPointer ? (UINT_PTR*)*target : target; tempobj->Invoke(aResultToken,aThisToken ,aFlags,aParam,aParamCount); tempobj->Release(); objclone->Release(); return OK; } return INVOKE_NOT_HANDLED; } } else // create field from structure { field = new FieldType(); deletefield = true; if (objclone == NULL) { // use this structure field->mMemAllocated = mMemAllocated; field->mIsInteger = mIsInteger; field->mIsPointer = mIsPointer; field->mEncoding = mEncoding; field->mIsUnsigned = mIsUnsigned; field->mOffset = 0; // structure with arrays so set to correct field size field->mSize = mSize / (mArraySize ? mArraySize : 1); field->mVarRef = 0; } else // use objclone created above { field->mMemAllocated = objclone->mMemAllocated; field->mIsInteger = objclone->mIsInteger; field->mIsPointer = objclone->mIsPointer; field->mEncoding = objclone->mEncoding; field->mIsUnsigned = objclone->mIsUnsigned; field->mOffset = 0; field->mSize = objclone->mSize / (objclone->mArraySize ? objclone->mArraySize : 1); } } } else if (!IS_INVOKE_CALL) // IS_INVOKE_CALL will handle the field itself field = FindField(TokenToString(*aParam[0])); } // // OPERATE ON A FIELD WITHIN THIS OBJECT // // CALL if (IS_INVOKE_CALL) { LPTSTR name = TokenToString(*aParam[0]); if (*name == '_') ++name; // ++ to exclude '_' from further consideration. ++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case. if (!_tcsicmp(name, _T("NewEnum"))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return _NewEnum(aResultToken, aParam, aParamCount); } // if first function parameter is a field get it if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0])) { if (field = FindField(TokenToString(*aParam[0]))) { // exclude parameter in aParam ++aParam; --aParamCount; } } aResultToken.symbol = SYM_INTEGER; // mostly used aResultToken.value_int64 = 0; // set default if (!_tcsicmp(name, _T("SetCapacity"))) { // Set strcuture its capacity or fields capacity if (!field) { if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { // 0 or no parameters were given to free memory if (mMemAllocated > 0) { mMemAllocated = 0; free(mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mMemAllocated > 0) free(mStructMem); // allocate memory and zero-fill if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(mStructMem,NULL,(size_t)mMemAllocated); aResultToken.value_int64 = mMemAllocated; } else mMemAllocated = 0; } else if (aParamCount) { // we must have to parmeters here since first parameter is field if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { if (field->mMemAllocated > 0) { field->mMemAllocated = 0; free(field->mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // not numeric } if (field->mMemAllocated > 0) free(field->mStructMem); // allocate memory and zero-fill if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { field->mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(field->mStructMem,NULL,(size_t)field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; aResultToken.value_int64 = mMemAllocated; } else field->mMemAllocated = 0; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetCapacity"))) { if (field) aResultToken.value_int64 = field->mMemAllocated; else aResultToken.value_int64 = mMemAllocated; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Offset"))) { if (field) aResultToken.value_int64 = field->mOffset; else if (aParamCount && TokenIsPureNumeric(*aParam[0])) // calculate size if item is an array aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("IsPointer"))) { if (field) aResultToken.value_int64 = field->mIsPointer; else aResultToken.value_int64 = mIsPointer; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Encoding"))) { if (field) aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding; else aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetPointer"))) { if (!field && aParamCount && mIsPointer) { // resolve array item if (mArraySize && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1)))); else aResultToken.value_int64 = *target; } else if (field) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset)); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Fill"))) { if (!field) // only allow to fill main structure { if (aParamCount && TokenIsPureNumeric(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize); else if (aParamCount && *TokenToString(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize); else memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetAddress"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1)); else aResultToken.value_int64 = (UINT_PTR)target; } else aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Size"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) // we do not care which item was requested because all are same size aResultToken.value_int64 = mSize / mArraySize; else aResultToken.value_int64 = mSize; } else aResultToken.value_int64 = field->mSize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("CountOf"))) { if (!field) aResultToken.value_int64 = mArraySize; else aResultToken.value_int64 = field->mArraySize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New"))) { if (!field) { if (!releaseobj) // else we have a clone already objclone = this->Clone(); } else { Struct* tempobj = objclone; if (releaseobj) // release object, it is not requred anymore { objclone = objclone->CloneField(field); tempobj->Release(); } else objclone = this->CloneField(field); } if (aParamCount) { // structure pointer and / or init object were given if (TokenIsPureNumeric(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]); objclone->mMemAllocated = 0; if (aParamCount > 1 && TokenToObject(*aParam[1])) objclone->ObjectToStruct(TokenToObject(*aParam[1])); } else if (TokenToObject(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); objclone->ObjectToStruct(TokenToObject(*aParam[0])); } } else { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); } // small fix for _New to work properly because aThisToken contains the new object if (!_tcsicmp(name, _T("_New"))) { if (aThisToken.symbol == SYM_OBJECT) aThisToken.object->Release(); else aThisToken.symbol = SYM_OBJECT; aThisToken.object = objclone; objclone->AddRef(); } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; if (deletefield) // we created the field from a structure delete field; // do not release objclone because it is returned return OK; } // For maintainability: explicitly return since above has done ++aParam, --aParamCount. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // identify that method was not found return INVOKE_NOT_HANDLED; } else if (!field) { // field was not found if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x]. else if (param_count_excluding_rvalue > 1) { // second parameter = "", so caller wants get/set field pointer if (TokenIsEmptyString(*aParam[1])) { aResultToken.symbol = SYM_INTEGER; if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) { // set simple pointer *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]); aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset); } else // set pointer to pointer { UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset; else { // get pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // clone field to object and invoke again { if (releaseobj) objclone->Release(); objclone = CloneField(field,true); /* if (!field->mArraySize && field->mIsPointer) { objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); //objclone->mIsPointer--; if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array objclone->mArraySize = 1; } else objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize)); */ objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); if (deletefield) // we created the field from a structure delete field; return OK; } } // MULTIPARAM[x,y] x[y] // SET else if (IS_INVOKE_SET) { if (field->mVarRef && TokenToObject(*aParam[1])) { // field is a structure, assign objct to structure if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer, clone to structure and invoke again if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); objclone->Release(); return OK; } // StrPut (code stolen from BIF_StrPut()) if (field->mEncoding != 65535) { // field is [T|W|U]CHAR or LP[TC]STR, set get character or string source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf); source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string)); - if (field->mSize > 2) // not [T|W|U]CHAR - source_length++; // for terminating character + //if (field->mSize > 2) // not [T|W|U]CHAR + // source_length++; // for terminating character if (!source_length) { // Take a shortcut when source_string is empty, since some paths below might not handle it correctly. if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return { aResultToken.value_int64 = 0; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mEncoding == CP_UTF16) *(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; else *(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; aResultToken.value_int64 = 1; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } - if (field->mSize > 2 && (!*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated<(source_length*2))))) + if (field->mSize > 2 && (!*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated < ((source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR))))))) { // no memory allocated yet, allocate now if (field->mMemAllocated == -1 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))){ if (deletefield) // we created the field from a structure so no memory can be allocated delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } else if (field->mMemAllocated > 0) // free previously allocated memory free(field->mStructMem); - field->mMemAllocated = source_length * sizeof(TCHAR); + field->mMemAllocated = (source_length + 1) * (field->mEncoding == 1200 ? sizeof(WCHAR) : sizeof(CHAR)); // + 1 for terminating character field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; } if (field->mEncoding == UorA(CP_UTF16, CP_ACP)) tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length); else { // Conversion is required. For Unicode builds, this means encoding != CP_UTF16; #ifndef UNICODE // therefore, this section is relevant only to ANSI builds: if (field->mEncoding == CP_UTF16) { // See similar section below for comments. char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0); if (!char_count) { aResultToken.value_int64 = char_count; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). length = char_count; char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length); if (field->mSize > 2 && char_count && char_count < length) ((LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)))[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 char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (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(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); } if (!char_count) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). // Assume there is sufficient buffer space and hope for the best: length = char_count; // Convert to target encoding. char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, 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 (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR - ((LPSTR)((UINT_PTR)target + field->mOffset))[char_count++] = '\0'; + ((LPSTR)*(UINT_PTR*)((UINT_PTR)target + field->mOffset))[char_count] = '\0'; #ifndef UNICODE } #endif } aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = char_count; } else { switch(field->mSize) { case 4: // Listed first for performance. if (field->mIsInteger) *((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]); else // Float (32-bit). *((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]); break; case 8: if (field->mIsInteger) // v1.0.48: Support unsigned 64-bit integers like DllCall does: *((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values. ? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall(). : TokenToInt64(*aParam[1]); else // Double (64-bit). *((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]); break; case 2: *((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]); break; default: // size 1 *((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]); } //*((int*)target + field->mOffset) = (int)TokenToInt64(*aParam[1]); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TokenToInt64(*aParam[1]); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } // GET else if (field) { if (field->mArraySize || field->mVarRef) { // filed is an array or variable reference, return a structure object. if (field->mArraySize || field->mIsPointer) { // field is array or a pointer to variable objclone = CloneField(field,true); objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } else // field is refference to a variable and not pointer, create structure { Var1.symbol = SYM_STRING; Var2.symbol = SYM_VAR; Var2.var = field->mVarRef; if (TokenToObject(Var2)) { // Variable is a structure object objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target + field->mOffset; aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; } else // Variable is a string definition { Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset); if (objclone = Struct::Create(param,2)) { // create and clone object because it is created dynamically Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; tempobj->Release(); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer of main structure for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer we need to return an object if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // StrGet (code stolen from BIF_StrGet()) if (field->mEncoding != 65535) { if (field->mEncoding != UorA(CP_UTF16, CP_ACP)) { // Conversion is required. int conv_length; if (field->mSize < 4) // TCHAR or CHAR or WCHAR length = 1; #ifdef UNICODE // Convert multi-byte encoded string to UTF-16. conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length); #else CStringW wide_buf; // If the target string is not UTF-16, convert it to that first. if (field->mEncoding != CP_UTF16) { StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding); (field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString(); length = wide_buf.GetLength(); } // Now convert UTF-16 to ACP. conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // Out of memory. } conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL); #endif if (conv_length && !aResultToken.marker[conv_length - 1]) --conv_length; // Exclude null-terminator. else aResultToken.marker[conv_length] = '\0'; aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // no conversation required { if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } aResultToken.symbol = SYM_STRING; if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1)) aResultToken.marker = _T(""); } aResultToken.symbol = SYM_STRING; } else // NumGet (code stolen from BIF_NumGet()) { switch(field->mSize) { case 4: // Listed first for performance. if (!field->mIsInteger) aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset)); else if (!field->mIsUnsigned) aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above. else aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset)); break; case 8: // The below correctly copies both DOUBLE and INT64 into the union. // Unsigned 64-bit integers aren't supported because variables/expressions can't support them. aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset)); break; case 2: if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset)); break; default: // size 1 if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset)); } aResultToken.symbol = SYM_INTEGER; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // // Struct:: Internal Methods // Struct::FieldType *Struct::FindField(LPTSTR val) { for (int i = 0;i < mFieldCount;i++) { FieldType &field = mFields[i]; if (!_tcsicmp(field.key,val)) return &field; } return NULL; } bool Struct::SetInternalCapacity(IndexType new_capacity) // Expands mFields to the specified number if fields. // Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount. { FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType)); if (!new_fields) return false; mFields = new_fields; mFieldCountMax = new_capacity; return true; } ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { if (aParamCount == 0) { IObject *newenum; if (newenum = new Enumerator(this)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = newenum; } } return OK; } int Struct::Enumerator::Next(Var *aKey, Var *aVal) { if (++mOffset < mObject->mFieldCount) { FieldType &field = mObject->mFields[mOffset]; if (aKey) aKey->Assign(field.key); if (aVal) { // We need to invoke the structure to retrieve the value ExprTokenType aResultToken; // not sure about the buffer TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } else if (mOffset < mObject->mArraySize) { // structure is an array if (aKey) aKey->Assign(mOffset + 1); // mOffset starts at 1 if (aVal) { // again we need to invoke structure to retrieve the value ExprTokenType aResultToken; TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_INTEGER; aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1 mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } return false; } Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding) // Inserts a single field with the given key at the given offset. // Caller must ensure 'at' is the correct offset for this key. { if (!*key) { // empty key = only type was given so assign all to structure object // do not assign size here since it will be assigned in StructCreate later mArraySize = aArrsize; mIsPointer = aIspointer; mIsInteger = aIsinteger; mIsUnsigned = aIsunsigned; mEncoding = aEncoding; mVarRef = variableref; return (FieldType*)true; } if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity. || !(key = _tcsdup(key))) // Attempt to duplicate key-string. { // Out of memory. return NULL; } // There is now definitely room in mFields for a new field. FieldType &field = mFields[at]; if (at < mFieldCount) // Move existing fields to make room. memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType)); ++mFieldCount; // Only after memmove above. // Update key-type offsets based on where and what was inserted; also update this key's ref count: field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign(). field.key = key; // Above has already copied string field.mArraySize = aArrsize; field.mIsPointer = aIspointer; field.mOffset = aOffset; field.mIsInteger = aIsinteger; field.mIsUnsigned = aIsunsigned; field.mEncoding = aEncoding; field.mVarRef = variableref; field.mMemAllocated = 0; return &field; } #ifdef CONFIG_DEBUGGER void Struct::DebugWriteProperty(IDebugProperties *aDebugger, int aPage, int aPageSize, int aDepth) { DebugCookie cookie; aDebugger->BeginProperty(NULL, "object", (int)mFieldCount, cookie); if (aDepth) { int i = aPageSize * aPage, j = aPageSize * (aPage + 1); if (j > (int)mFieldCount) j = (int)mFieldCount; // For each field in the requested page... for ( ; i < j; ++i) { Struct::FieldType &field = mFields[i]; ExprTokenType value; TCHAR buf[MAX_PATH]; value.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = this; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; this->Invoke(value,aThisToken,0,&aVarToken,1); delete aVarToken; if (field.mEncoding != 65535) // String aDebugger->WriteProperty(CStringUTF8FromTChar(field.key), value); } } aDebugger->EndProperty(cookie); } #endif
tinku99/ahkdll
e17cbfec04caf1ef2ceeffeb1523ef029efb4df8
Fix alignment and pointers
diff --git a/README b/README index 57908a1..c6bfd97 100644 --- a/README +++ b/README @@ -1,169 +1,173 @@ +17.08.2012 +- Fixed to use alignment for all types and also in 32-bit environment +- Fixed pointer handling in some cases +- To set Pointer in main structure you will need to use struct["",""]:=ptr 09.08.2012 - Merged AutoHotkey_L 1.1.08.01 - Fixed a bug in ahkFunction, variables were not freed. - Fixed freeing some internal variables on restart or ExitApp in AutoHotkey.dll. - Fixed OnMessage was not correctly handled on reload and ExitApp in AutoHotkey.dll. - Static variables are now saved separately from local variables - - When a function uses many static variables the time used to call the function is greatly improved. - - This is because only local variables need to be freed and we do not need to check if a variable is static. - - ListVars also shows static variables separate from local, this also helps debugging. - New Build-in functions - - Struct() and sizeof(), see manual for usage. 15.02.2012 - ResourceLibrary - Removed ahkKey - FileInstall for Scripts compiled with AutoHotkey.exe - Allow pure integers (pointers) for DllCall and DynaCall "Str" prameter. 01.10.2011 - Merged latest MemoryModule - Fixed x64w build AutoHotkey.dll also works fine using COM 25.10.2010 - Fixed ahkFunction returning wrong value - Default script set to #Persistent`n#NoTrayIcon - Fixed ahkExec to return when no line was added 15.08.2010 - Merged AutoHotkey_L54 - DllCall will now always search for W and A functions first, this is due to some functions do not have A suffix e.g. Process32First and Process32FirstW - when empty string is passed to ahkdll function, it will run in text mode same as ahktextdll so it will run "#Persistent". - ahkLabel second parameter is called nowait now so when 0 (default) AutoHotkey will wait for code to finish execution, because using PostMessage times out often when CPU is under load. 12.08.2010 - Merged AutoHotkey_L Revision 53 - new exported function ahkExec used to temporarily run some script, accepts also several lines of code - when empty string is passed in first parameter, AutoHotkey will run "#Pesistent" as script. 18.07.2010 - Fixed a bug for dll when it was in root folder - DynaCall is now managed trough internal DynaToken, similar to objects but without object features and much faster but can be used with DynaCall only (thanks Lexikos) - DynaCall can set default parameters now, so you can call the function later with less or even witout parameters: func.() 16.07.2010 - Fixed not to delete ClipBoard vars when ahkdll is reloaded 11.07.2010 - Merged latest fixes by tinku99 19.06.2010 - H17 - Merged with AHK_L52 10.06.2010 - Fixed addScript and addFile loop bug - Fixed ahkFunction bug when returning empty parameters and strings 27.05.2010 - Fixed when terminating dll not to destroy Build in variables - Fixed problem when dll reloads, now parameter strings given to ahkdll and ahktextdll are copied and not used. 14.05.2010 - Fix for Alias BIF - Multithread support for Input command, see other changes in docs. 28.03.2010 - Merge AutoHotkey_L Revision 50 - DynaCall fix, *pP parameter was not initialized correctly 28.02.2010 - DynaCall returns Objects now. - You can use object features like dll.ahkgetvar.var or dll.ahkFunction["func"] or dll.ahkassign.var := value 13.02.2010 - ResourceLoadLibrary for AutoHotkeySC.bin 10.02.2010 - fix for A_DllPath - fix on DLL_PROCESS_DETACH invalid hThread (MemoryFreeLibrary works fine now) 07.02.2010 - fixed ahkFunction - added ahkPostFunction same syntax as ahkFunction but returns unsigned int 0 if func found, else -1 - ahkPostFunction and ahkFunction parameters are all optional now. - ahkFunction and ahkPostFunction use now a CRITICAL_SECTION to avoid collision - SendMode Input is default now. - #NoEnv is default now, use '#NoEnv, Off' to turn off - fixed ahkExecuteLine to run when lastline is given - ahkLabel returns 0 if Label found else -1 - added ahkFindLabel - ahkTerminate will now try (for 500ms) to stop the thread via PostMessage before running TerminateThread. - EXPERIMENTAL New build in functions: MemoryLoadLibrary - MemoryGetProcAddress - MemoryFreeLibrary - - Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html - - So now multithreading is even easier as only 1 dll is needed. - - Hook does not work currently. - DynaCall, runs faster than DllCall and uses internally saved array of DllCall structures based on functions pointer. 03.02.2010 - Unicode 18.01.2010 - fixed MsgSleep to work after termination and reload. - enabled #Persistent so a script that does not use #Persistent will terminate (use ahkdll ahktextdll or ahkReload to run it again). - Send commands support inline sleep now when pure digits are specified, like Send a{30}{Tab}b{100}{Enter}. Send {9} will not sleep but send 9. - Reload, Exit and ExitApp works like they should now for the dll. - Added 2 new stdlib folder, which is the parent folder of A_AhkPath + Lib.lnk in same folder if it links to a directory. - - - Directory of A_AhkPath, so now stdlib functions can be placed in same folder for simplicity. - - - Additionally you can specify a link file in same folder (Lib.lnk) to your stdlib instead of copying the files for a portable project (e.g. on a ram drive!). - ahktextdll and addScript support loading functions from all 4 libraries now as well. - AutoHotkey.exe started without parameters checks for following files: - - 1 %A_AhkPath%\..\[Name of executable].ahk - - 2 %A_AhkPath%\..\[Name of executable].ini - - 3 %A_MyDocuments%\AutoHotkey.ahk - - - REMINDER: portable mode = copy + rename AutoHotkey.exe to e.g. MyScript.exe and put it together with MyScript.ahk or .ini in same folder. - No need to call ahkTerminate before calling ahkdll or ahktextdll, it will terminate automatically if a script is running. - New AhkDll function - AhkDll(dllfile,function,p1,p2...), using static pointers to functions, executes around 5 times faster. - - Loads dll library automatically so no need to call DllCall("LoadLibrary"...) - - Dllfile must contain only characters valid for a variable in ahk [a-zA-Z0-9_#$@]! - - Functions are all case sensitive! - ahkgetvar has now a further parameter (UInt), when this parameter is not 0, the pointer of the variable will be returned to use with Alias(), else value is returned - New AutoHotkeyMini.dll uses a preprocessor and excludes many commands to support much faster load/reload and less memory usage. - Following commands are disabled/removed: - - Hotkey (as well as Hotkey + Hotstring functionality), Gui…, GuiControl[Get], Menu…, TrayIcon, FileInstall, ListVars, ListLines, ListHotkeys, - - KeyHistory, SplashImage, SplashText…, Progress, PixelSearch, PixelGetColor, InputBox, - - FileSelect and FolderSelect dialogs, Input, BlockInput MouseMove[Off], - - Build in variables related to Hotkeys and Icons as well as Gui, A_ThisHotkey…, A_IsSuspended, A_Icon…. 30.12.2009 - ahkReload will reload a script, this can be also done by the script as well as ExitApp. - ahkPause, get and set Pause state of current thread in dll script (dll only) - ahkExecuteLine, execute a line by passing its pointer, a pointer is returned by addFile and addScript as well as by this function. - - when no pointer is given, FirstLine pointer is returned, else pointer to next line is returned. - changed ahkgetvar to return a value rather than passing a variable, so no need to VarSetCapacity anymore. - fixed ahkFunction ( now using callFuncDll() ) to continue main script after function call. - fixed to wait for thread to initialize and return then, as well as when script crashes while initializing. - addScript will not reset previous script anymore. - removed const for HotkeyIDType Hotkey so sHotkeyCount can be reset for ahkTerminate. 21.12.2009 - ahkTerminate, after terminating your script you can reload it using ahkdll or ahktextdll. - script, incl. labels and functions, and hotkey destruction and reload now possible. - a bug in ahkFunction was fixed. 19.12.2009 - fixed addScript bugs - created ahktextdll 18.12.2009 - addScript loads script from text, second parameter is to replace current script DllCall(A_AhkPath "\addScript","Str","a:`nMsgBox a`nReturn","ushort",1,"Cdecl UInt") - \ahkdll function will now load text if specified file does not exist - no need for #Persistent in AutoHotkey.dll 17.12.2009 - Changed to "Portable Mode" - Instead looking for %My_Documents%\AutoHotkey.ahk, the exe checks for %ExeDir%\ExeName.ahk. - So you can copy AutoHotkey.exe and Script to separate folder then rename the exe to ScriptName.exe and start by double clicking the exe. - You can also start new scripts using your exe that way. e.g. Run YourExe.exe "%filepath%" - Changed ahkgetvar to support alias and build in variables. - Removed ebiv.cpp because ahkgetvar can be used to get any variable beside clipboard and clipboardall - Changed ahkFunction to support up to 10 parameters + return values \ No newline at end of file diff --git a/source/script_object_bif.cpp b/source/script_object_bif.cpp index 6ba8794..77ab508 100644 --- a/source/script_object_bif.cpp +++ b/source/script_object_bif.cpp @@ -1,699 +1,688 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "globaldata.h" #include "script.h" #include "script_object.h" // // BIF_Struct - Create structure // BIF_DECL(BIF_Struct) { // At least the definition for structure must be given if (!aParamCount) return; IObject *obj = Struct::Create(aParam,aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } // indicate error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_sizeof - sizeof() for structures and default types // BIF_DECL(BIF_sizeof) // This code is very similar to BIF_Struct so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[10]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure -#ifdef _WIN64 int aligntotal = 0; // pointer alignment for total structure -#endif int thissize; // used to save size returned from IsDefaultType // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2}; // will hold pointer to structure definition while we parse it TCHAR *buf; size_t buf_size; // Should be enough buffer to accept any definition and name. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; // Set result to empty string to identify error aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; // if first parameter is an object (struct), simply return its size if (TokenToObject(*aParam[0])) { aResultToken.symbol = SYM_INTEGER; Struct *obj = (Struct*)TokenToObject(*aParam[0]); aResultToken.value_int64 = obj->mSize; return; } if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // an offset was given, set starting offset offset = (int)TokenToInt64(*aParam[1]); Var2.value_int64 = (__int64)offset; } // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // now restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set default arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) return; _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) return; else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } // Pointer, while loop will continue here because we only need size if (_tcschr(tempbuf,'*')) { offset += ptrsize * (arraydef ? arraydef : 1); -#ifdef _WIN64 // align offset for pointer if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; -#endif // update offset if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now and continue if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); continue; } // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t ["))) > MAX_VAR_NAME_LENGTH*2 + 30) return; _tcsncpy(defbuf + 1,tempbuf,_tcscspn(tempbuf,_T("\t ["))); _tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t [")),_T(" ")); } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt _tcscpy(defbuf,_T(" UInt ")); // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { + if (!_tcscmp(defbuf,_T(" bool "))) + thissize = 1; offset += thissize * (arraydef ? arraydef : 1); -#ifdef _WIN64 - // align offset for pointer - if (offset % thissize) + // align offset + if (thissize > 1 && offset % thissize) + { offset += thissize - (offset % thissize); - if (thissize > aligntotal) - aligntotal = thissize; -#endif + if (thissize > aligntotal) + aligntotal = thissize; + } } else // type was not found, check for user defined type in variables { Var1.var = NULL; Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); } else // release object and return { if (bkpfunc) g->CurrentFunc = bkpfunc; return; } } if (g->CurrentFunc) { Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // restore CurrentFunc if (bkpfunc) g->CurrentFunc = bkpfunc; } // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); if (Var1.var != NULL) { // Call BIF_sizeof passing offset in second parameter to align if necessary param[1]->value_int64 = (__int64)offset; BIF_sizeof(Result,ResultToken,param,2); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure return; } // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)ResultToken.value_int64 * (arraydef ? arraydef : 1); - /* -#ifdef _WIN64 - // align offset for pointer, not necessary to align total because this is the only field - if (offset % ResultToken.value_int64) - offset += ResultToken.value_int64 - (offset % ResultToken.value_int64); -#endif - */ } else // No variable was found and it is not default type so we can't determine size, return empty string. return; } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else buf += _tcslen(buf); } -#ifdef _WIN64 - if (aligntotal) - offset += offset % aligntotal; -#endif + if (aligntotal && offset % aligntotal) // align only if offset was not given + offset += aligntotal - (offset % aligntotal); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = offset; } // // BIF_ObjCreate - Object() // BIF_DECL(BIF_ObjCreate) { IObject *obj = NULL; if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { if (obj = TokenToObject(*aParam[0])) { // Allow &obj == Object(obj), but AddRef() for equivalence with ComObjActive(comobj). obj->AddRef(); aResultToken.value_int64 = (__int64)obj; return; // symbol is already SYM_INTEGER. } obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = Object::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // BIF_ObjArray - Array(items*) // BIF_DECL(BIF_ObjArray) { Object *obj = Object::Create(); if (obj) { if (!aParamCount || obj->InsertAt(0, 1, aParam, aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; return; } obj->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } // // BIF_IsObject - IsObject(obj) // BIF_DECL(BIF_IsObject) // IsObject(obj) is currently equivalent to (obj && obj=""), but much more intuitive. { int i; for (i = 0; i < aParamCount && TokenToObject(*aParam[i]); ++i); aResultToken.value_int64 = (__int64)(i == aParamCount); // TRUE if all are objects. } // // BIF_ObjInvoke - Handles ObjGet/Set/Call() and get/set/call syntax. // BIF_DECL(BIF_ObjInvoke) { int invoke_type; IObject *obj; ExprTokenType *obj_param; // Since ObjGet/ObjSet/ObjCall are not publicly accessible as functions, Func::mName // (passed via aResultToken.marker) contains the actual flag rather than a name. invoke_type = (int)(INT_PTR)aResultToken.marker; // Set default return value; ONLY AFTER THE ABOVE. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); obj_param = *aParam; // aParam[0]. Load-time validation has ensured at least one parameter was specified. ++aParam; --aParamCount; // The following is used in place of TokenToObject to bypass #Warn UseUnset: if (obj_param->symbol == SYM_OBJECT) obj = obj_param->object; else if (obj_param->symbol == SYM_VAR && obj_param->var->HasObject()) obj = obj_param->var->Object(); else obj = NULL; if (obj) { bool param_is_var = obj_param->symbol == SYM_VAR; if (param_is_var) // Since the variable may be cleared as a side-effect of the invocation, call AddRef to ensure the object does not expire prematurely. // This is not necessary for SYM_OBJECT since that reference is already counted and cannot be released before we return. Each object // could take care not to delete itself prematurely, but it seems more proper, more reliable and more maintainable to handle it here. obj->AddRef(); aResult = obj->Invoke(aResultToken, *obj_param, invoke_type, aParam, aParamCount); if (param_is_var) obj->Release(); } // Invoke meta-functions of g_MetaObject. else if (INVOKE_NOT_HANDLED == (aResult = g_MetaObject.Invoke(aResultToken, *obj_param, invoke_type | IF_META, aParam, aParamCount))) { // Since above did not handle it, check for attempts to access .base of non-object value (g_MetaObject itself). if ( invoke_type != IT_CALL // Exclude things like "".base(). && aParamCount > (invoke_type == IT_SET ? 2 : 0) // SET is supported only when an index is specified: "".base[x]:=y && !_tcsicmp(TokenToString(*aParam[0]), _T("base")) ) { if (aParamCount > 1) // "".base[x] or similar { // Re-invoke g_MetaObject without meta flag or "base" param. ExprTokenType base_token; base_token.symbol = SYM_OBJECT; base_token.object = &g_MetaObject; g_MetaObject.Invoke(aResultToken, base_token, invoke_type, aParam + 1, aParamCount - 1); } else // "".base { // Return a reference to g_MetaObject. No need to AddRef as g_MetaObject ignores it. aResultToken.symbol = SYM_OBJECT; aResultToken.object = &g_MetaObject; } } else { // Since it wasn't handled (not even by g_MetaObject), maybe warn at this point: if (obj_param->symbol == SYM_VAR) obj_param->var->MaybeWarnUninitialized(); } } if (aResult == INVOKE_NOT_HANDLED) aResult = OK; } // // BIF_ObjGetInPlace - Handles part of a compound assignment like x.y += z. // BIF_DECL(BIF_ObjGetInPlace) { // Since the most common cases have two params, the "param count" param is omitted in // those cases. Otherwise we have one visible parameter, which indicates the number of // actual parameters below it on the stack. aParamCount = aParamCount ? (int)TokenToInt64(*aParam[0]) : 2; // x[<n-1 params>] : x.y BIF_ObjInvoke(aResult, aResultToken, aParam - aParamCount, aParamCount); } // // BIF_ObjNew - Handles "new" as in "new Class()". // BIF_DECL(BIF_ObjNew) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ExprTokenType *class_token = aParam[0]; // Save this to be restored later. IObject *class_object = TokenToObject(*class_token); if (!class_object) return; Object *new_object = Object::Create(); if (!new_object) return; new_object->SetBase(class_object); ExprTokenType name_token, this_token; this_token.symbol = SYM_OBJECT; this_token.object = new_object; name_token.symbol = SYM_STRING; aParam[0] = &name_token; ResultType result; LPTSTR buf = aResultToken.buf; // In case Invoke overwrites it via the union. // __Init was added so that instance variables can be initialized in the correct order // (beginning at the root class and ending at class_object) before __New is called. // It shouldn't be explicitly defined by the user, but auto-generated in DefineClassVars(). name_token.marker = _T("__Init"); result = class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, 1); if (result != INVOKE_NOT_HANDLED) { // See similar section below for comments. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Reset to defaults for __New, invoked below. aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); aResultToken.buf = buf; if (result == FAIL) { aParam[0] = class_token; // Restore it to original caller-supplied value. return; } } // __New may be defined by the script for custom initialization code. name_token.marker = Object::sMetaFuncName[4]; // __New if (class_object->Invoke(aResultToken, this_token, IT_CALL | IF_METAOBJ, aParam, aParamCount) != EARLY_RETURN) { // Although it isn't likely to happen, if __New points at a built-in function or if mBase // (or an ancestor) is not an Object (i.e. it's a ComObject), aResultToken can be set even when // the result is not EARLY_RETURN. So make sure to clean up any result we're not going to use. if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->Release(); if (aResultToken.mem_to_free) { // This can be done by our caller, but is done here for maintainability; i.e. because // some callers might expect mem_to_free to be NULL when the result isn't a string. free(aResultToken.mem_to_free); aResultToken.mem_to_free = NULL; } // Either it wasn't handled (i.e. neither this class nor any of its super-classes define __New()), // or there was no explicit "return", so just return the new object. aResultToken.symbol = SYM_OBJECT; aResultToken.object = this_token.object; } else new_object->Release(); aParam[0] = class_token; } // // BIF_ObjIncDec - Handles pre/post-increment/decrement for object fields, such as ++x[y]. // BIF_DECL(BIF_ObjIncDec) { // Func::mName (which aResultToken.marker is set to) has been overloaded to pass // the type of increment/decrement to be performed on this object's field. SymbolType op = (SymbolType)(INT_PTR)aResultToken.marker; ExprTokenType temp_result, current_value, value_to_set; // Set the defaults expected by BIF_ObjInvoke: temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_GET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Retrieve the current value. Do it this way instead of calling Object::Invoke // so that if aParam[0] is not an object, g_MetaObject is correctly invoked. BIF_ObjInvoke(aResult, temp_result, aParam, aParamCount); if (aResult == FAIL || aResult == EARLY_EXIT) return; // Change SYM_STRING to SYM_OPERAND so below may treat it as a numeric string. if (temp_result.symbol == SYM_STRING) { temp_result.symbol = SYM_OPERAND; temp_result.buf = NULL; // Indicate that this SYM_OPERAND token LACKS a pre-converted binary integer. } switch (value_to_set.symbol = current_value.symbol = TokenIsPureNumeric(temp_result)) { case PURE_INTEGER: value_to_set.value_int64 = (current_value.value_int64 = TokenToInt64(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; case PURE_FLOAT: value_to_set.value_double = (current_value.value_double = TokenToDouble(temp_result)) + ((op == SYM_POST_INCREMENT || op == SYM_PRE_INCREMENT) ? +1 : -1); break; } // Free the object or string returned by BIF_ObjInvoke, if applicable. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); if (current_value.symbol == PURE_NOT_NUMERIC) { // Value is non-numeric, so assign and return "". value_to_set.symbol = SYM_STRING; value_to_set.marker = _T(""); //current_value.symbol = SYM_STRING; // Already done (SYM_STRING == PURE_NOT_NUMERIC). current_value.marker = _T(""); } // Although it's likely our caller's param array has enough space to hold the extra // parameter, there's no way to know for sure whether it's safe, so we allocate our own: ExprTokenType **param = (ExprTokenType **)_alloca((aParamCount + 1) * sizeof(ExprTokenType *)); memcpy(param, aParam, aParamCount * sizeof(ExprTokenType *)); // Copy caller's param pointers. param[aParamCount++] = &value_to_set; // Append new value as the last parameter. if (op == SYM_PRE_INCREMENT || op == SYM_PRE_DECREMENT) { aResultToken.marker = (LPTSTR)IT_SET; // Set the new value and pass the return value of the invocation back to our caller. // This should be consistent with something like x.y := x.y + 1. BIF_ObjInvoke(aResult, aResultToken, param, aParamCount); } else // SYM_POST_INCREMENT || SYM_POST_DECREMENT { // Must be re-initialized (and must use IT_SET instead of IT_GET): temp_result.symbol = SYM_INTEGER; temp_result.marker = (LPTSTR)IT_SET; temp_result.buf = aResultToken.buf; temp_result.mem_to_free = NULL; // Set the new value. BIF_ObjInvoke(aResult, temp_result, param, aParamCount); // Dispose of the result safely. if (temp_result.symbol == SYM_OBJECT) temp_result.object->Release(); if (temp_result.mem_to_free) free(temp_result.mem_to_free); // Return the previous value. aResultToken.symbol = current_value.symbol; aResultToken.value_int64 = current_value.value_int64; // Union copy. } } // // Functions for accessing built-in methods (even if obscured by a user-defined method). // #define BIF_METHOD(name) \ BIF_DECL(BIF_Obj##name) \ { \ aResultToken.symbol = SYM_STRING; \ aResultToken.marker = _T(""); \ \ Object *obj = dynamic_cast<Object*>(TokenToObject(*aParam[0])); \ if (obj) \ obj->_##name(aResultToken, aParam + 1, aParamCount - 1); \ } BIF_METHOD(Insert) BIF_METHOD(Remove) BIF_METHOD(GetCapacity) BIF_METHOD(SetCapacity) BIF_METHOD(GetAddress) BIF_METHOD(MaxIndex) BIF_METHOD(MinIndex) BIF_METHOD(NewEnum) BIF_METHOD(HasKey) BIF_METHOD(Clone) // // ObjAddRef/ObjRelease - used with pointers rather than object references. // BIF_DECL(BIF_ObjAddRefRelease) { IObject *obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)4096) // Rule out some obvious errors. { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[3]) == 'A') aResultToken.value_int64 = obj->AddRef(); else aResultToken.value_int64 = obj->Release(); } \ No newline at end of file diff --git a/source/script_struct.cpp b/source/script_struct.cpp index f33c8dc..8459019 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -1,1908 +1,1907 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "application.h" #include "globaldata.h" #include "script.h" #include "TextIO.h" #include "script_object.h" // // Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set. // Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount) // This code is very similar to BIF_sizeof so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[100]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int ispointer = NULL; // identify pointer and how deep it goes -#ifdef _WIN64 int aligntotal = 0; // pointer alignment for total structure -#endif int thissize; // used to check if type was found in above array. // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; // will hold pointer to structure definition string while we parse trough it TCHAR *buf; size_t buf_size; // Use enough buffer to accept any definition in a field. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable) TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; FieldType *field; // used to define a field // Structure object is saved in fixed order // insert_pos is simply increased each time // for loop will enumerate items in same order as it was created IndexType insert_pos = 0; // the new structure object Struct *obj = new Struct(); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; if (TokenToObject(*aParam[0])) { obj->Release(); obj = ((Struct *)TokenToObject(*aParam[0]))->Clone(); if (aParamCount > 2) { obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); obj->ObjectToStruct(TokenToObject(*aParam[2])); } else if (aParamCount > 1) { if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,offset); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); } else { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); } return obj; } // Set initial capacity to avoid multiple expansions. // For simplicity, failure is handled by the loop below. obj->SetInternalCapacity(aParamCount >> 1); // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; // backup offset unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set defaults ispointer = false; arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) { obj->Release(); return NULL; } _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) { obj->Release(); return NULL; } else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Pointer if (_tcschr(tempbuf,'*')) ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition from temp buffer to identify key easier StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Trim trailing spaces in case we had a definition like UInt [10] rtrim(tempbuf); } // copy type // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30) { obj->Release(); return NULL; } _tcsncpy(defbuf + 1,tempbuf,buf_size); //_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" ")); defbuf[1 + buf_size] = ' '; defbuf[2 + buf_size] = '\0'; if (StrChrAny(tempbuf, _T(" \t"))) { if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30) { obj->Release(); return NULL; } _tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1); ltrim(keybuf); } else keybuf[0] = '\0'; } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt { _tcscpy(defbuf,_T(" UInt ")); _tcscpy(keybuf,tempbuf); } // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { - if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize - ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) - ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) - ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) - { // Out of memory. - obj->Release(); - return NULL; - } - offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); -#ifdef _WIN64 - // align offset for pointer + if (!_tcscmp(defbuf,_T(" bool "))) + thissize = 1; + // align offset if (ispointer) { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } else { if (offset % thissize) offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } -#endif + if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize + ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) + ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) + ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) + { // Out of memory. + obj->Release(); + return NULL; + } + offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); } else // type was not found, check for user defined type in variables { Var1.var = NULL; // init to not found Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("*MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); g->CurrentFunc = bkpfunc; } else // release object and return { g->CurrentFunc = bkpfunc; obj->Release(); return NULL; } } else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); // variable found if (Var1.var != NULL) { if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf) { // Whole definition is not a pointer and no key was given so create Structure from variable obj->Release(); if (aParamCount == 1) { if (TokenToObject(*param[0])) { // assume variable is a structure object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); return obj; } // else create structure from string definition return Struct::Create(param,1); } else if (aParamCount > 1) { // more than one parameter was given, copy aParam to param param[1]->symbol = aParam[1]->symbol; param[1]->object = aParam[1]->object; param[1]->value_int64 = aParam[1]->value_int64; param[1]->var = aParam[1]->var; } if (aParamCount > 2) { // more than 2 parameters were given, copy aParam to param param[2]->symbol = aParam[2]->symbol; param[2]->object = aParam[2]->object; param[2]->var = aParam[2]->var; // definition variable is a structure object, clone it, assign memory and init object if (TokenToObject(*param[0])) { obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mMemAllocated = 0; obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; obj->ObjectToStruct(TokenToObject(*aParam[2])); return obj; } return Struct::Create(param,3); } else if (TokenToObject(*param[0])) { // definition variable is a structure object, clone it and assign memory or init object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; return obj; } // else simply create structure from variable and given memory/initobject return Struct::Create(param,2); } // Call BIF_sizeof passing offset in second parameter to align offset if necessary // if field is a pointer we will need its size only - param[1]->value_int64 = (__int64)ispointer ? 0 : offset; - BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 2); - if (ResultToken.symbol != SYM_INTEGER) - { // could not resolve structure - obj->Release(); - return NULL; + if (!ispointer) + { + param[1]->value_int64 = (__int64)ispointer ? 0 : offset; + BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 2); + if (ResultToken.symbol != SYM_INTEGER) + { // could not resolve structure + obj->Release(); + return NULL; + } + } + else + { + if (offset % ptrsize) + offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); + if (ptrsize > aligntotal) + aligntotal = ptrsize; } // Insert new field in our structure - if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? 4 : (int)ResultToken.value_int64,1,1,-1))) + if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? ptrsize : (int)ResultToken.value_int64,1,1,-1))) { // Out of memory. obj->Release(); return NULL; } if (ispointer) - offset += (int)(ispointer ? ptrsize : ResultToken.value_int64) * (arraydef ? arraydef : 1); + offset += (int)ptrsize * (arraydef ? arraydef : 1); else // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += - offset = (int)(ispointer ? ptrsize : ResultToken.value_int64) * (arraydef ? arraydef : 1); -#ifdef _WIN64 - // align offset for pointer - if (ispointer) - { - if (offset % ptrsize) - offset += ptrsize - (offset % ptrsize); - } -#endif + offset = (int)ResultToken.value_int64 * (arraydef ? arraydef : 1); } else // No variable was found and it is not default type so we can't determine size. { obj->Release(); return NULL; } } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else { // identify that structure object has no fields if (!*keybuf) obj->mTypeOnly = true; buf += _tcslen(buf); } } -#ifdef _WIN64 // align total structure if necessary - if (aligntotal) - offset += offset % aligntotal; -#endif + if (aligntotal && offset % aligntotal) + offset += aligntotal - (offset % aligntotal); if (!offset) // structure could not be build { obj->Release(); return NULL; } obj->mSize = offset; if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // second parameter exist and it is digit assumme this is new pointer for our structure obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]); obj->mMemAllocated = 0; } else // no pointer given so allocate memory and fill memory with 0 { // setting the memory after parsing definition saves a call to BIF_sizeof obj->mStructMem = (UINT_PTR *)malloc(offset); obj->mMemAllocated = offset; memset(obj->mStructMem,NULL,offset); } // an object was passed to initialize fields // enumerate trough object and assign values if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 ) obj->ObjectToStruct(TokenToObject(aParamCount == 2 ? *aParam[1] : *aParam[2])); return obj; } // // Struct::ObjectToStruct - Initialize structure from array, object or structure. // void Struct::ObjectToStruct(IObject *objfrom) { ExprTokenType ResultToken, this_token,enum_token,param_tokens[3]; ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 }; TCHAR defbuf[MAX_PATH],buf[MAX_PATH]; int param_count = 3; // Set up enum_token the way Invoke expects: enum_token.symbol = SYM_STRING; enum_token.marker = _T(""); enum_token.mem_to_free = NULL; enum_token.buf = defbuf; // Prepare to call object._NewEnum(): param_tokens[0].symbol = SYM_STRING; param_tokens[0].marker = _T("_NewEnum"); objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1); if (enum_token.mem_to_free) // Invoke returned memory for us to free. free(enum_token.mem_to_free); // Check if object returned an enumerator, otherwise return if (enum_token.symbol != SYM_OBJECT) return; // create variables to use in for loop / for enumeration // these will be deleted afterwards Var *var1 = (Var*)alloca(sizeof(Var)); Var *var2 = (Var*)alloca(sizeof(Var)); var1->mType = var2->mType = VAR_NORMAL; var1->mAttrib = var2->mAttrib = 0; var1->mByteCapacity = var2->mByteCapacity = 0; var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC; // Prepare parameters for the loop below: enum.Next(var1 [, var2]) param_tokens[0].marker = _T("Next"); param_tokens[1].symbol = SYM_VAR; param_tokens[1].var = var1; param_tokens[1].mem_to_free = 0; param_tokens[2].symbol = SYM_VAR; param_tokens[2].var = var2; param_tokens[2].mem_to_free = 0; ExprTokenType result_token; IObject &enumerator = *enum_token.object; // Might perform better as a reference? this_token.symbol = SYM_OBJECT; this_token.object = this; for (;;) { // Set up result_token the way Invoke expects; each Invoke() will change some or all of these: result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; // Call enumerator.Next(var1, var2) enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count); bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token)); if (!next_returned_true) break; this->Invoke(ResultToken,this_token,IT_SET,params+1,2); // release object if it was assigned prevoiously when calling enum.Next if (var1->IsObject()) var1->ReleaseObject(); if (var2->IsObject()) var2->ReleaseObject(); // Free any memory or object which may have been returned by Invoke: if (result_token.mem_to_free) free(result_token.mem_to_free); if (result_token.symbol == SYM_OBJECT) result_token.object->Release(); } // release enumerator and free vars enumerator.Release(); var1->Free(); var2->Free(); } // // Struct::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool Struct::Delete() { return ObjectBase::Delete(); } Struct::~Struct() { if (mMemAllocated > 0) free(mStructMem); if (mFields) { if (mFieldCount) { IndexType i = mFieldCount - 1; // Free keys for ( ; i >= 0 ; --i) { if (mFields[i].mMemAllocated > 0) free(mFields[i].mStructMem); free(mFields[i].key); } } // Free fields array. free(mFields); } } // // Struct::SetPointer - used to set pointer for a field or array item // UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem) { - *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; + if (mIsPointer) + *((UINT_PTR*)(*mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; + else + *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; return aPointer; } // // Struct::FieldType::Clone - used to clone a field to structure. // Struct *Struct::CloneField(FieldType *field,bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; // if field is an array, set correct size if (obj.mArraySize = field->mArraySize) obj.mSize = field->mSize*obj.mArraySize; else obj.mSize = field->mSize; obj.mIsInteger = field->mIsInteger; obj.mIsPointer = field->mIsPointer; obj.mEncoding = field->mEncoding; obj.mIsUnsigned = field->mIsUnsigned; obj.mVarRef = field->mVarRef; obj.mTypeOnly = 1; obj.mMemAllocated = aIsDynamic ? -1 : 0; return objptr; } // // Struct::Clone - used for cloning structures. // Struct *Struct::Clone(bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; obj.mArraySize = mArraySize; obj.mIsInteger = mIsInteger; obj.mIsPointer = mIsPointer; obj.mEncoding = mEncoding; obj.mIsUnsigned = mIsUnsigned; obj.mSize = mSize; obj.mVarRef = mVarRef; obj.mTypeOnly = mTypeOnly; // -1 will identify a dynamic structure, no memory can be allocated to such obj.mMemAllocated = aIsDynamic ? -1 : 0; // Allocate space in destination object. if (!obj.SetInternalCapacity(mFieldCount)) { obj.Release(); return NULL; } FieldType *fields = obj.mFields; // Newly allocated by above. int failure_count = 0; // See comment below. IndexType i; obj.mFieldCount = mFieldCount; for (i = 0; i < mFieldCount; ++i) { FieldType &dst = fields[i]; FieldType &src = mFields[i]; if ( !(dst.key = _tcsdup(src.key)) ) { // Key allocation failed. // Rather than trying to set up the object so that what we have // so far is valid in order to break out of the loop, continue, // make all fields valid and then allow them to be freed. ++failure_count; } dst.mArraySize = src.mArraySize; dst.mIsInteger = src.mIsInteger; dst.mIsPointer = src.mIsPointer; dst.mEncoding = src.mEncoding; dst.mIsUnsigned = src.mIsUnsigned; dst.mOffset = src.mOffset; dst.mSize = src.mSize; dst.mVarRef = src.mVarRef; dst.mMemAllocated = aIsDynamic ? -1 : 0; } if (failure_count) { // One or more memory allocations failed. It seems best to return a clear failure // indication rather than an incomplete copy. Now that the loop above has finished, // the object's contents are at least valid and it is safe to free the object: obj.Release(); return NULL; } return &obj; } // // Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object. // ResultType STDMETHODCALLTYPE Struct::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) // L40: Revised base mechanism for flexibility and to simplify some aspects. // obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc. { int ptrsize = sizeof(UINT_PTR); FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL ResultType Result = OK; // Used to resolve dynamic structures ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2},ResultToken; // used to clone a dynamic field or structure Struct *objclone = NULL; // used for StrGet/StrPut LPCVOID source_string; int source_length; DWORD flags = WC_NO_BEST_FIT_CHARS; int length = -1; int char_count; // Identify that we need to release/delete field or structure object bool deletefield = false; bool releaseobj = false; int param_count_excluding_rvalue = aParamCount; // target may be altered here to resolve dynamic structure so hold it separately UINT_PTR *target = mStructMem; if (IS_INVOKE_SET) { // Prior validation of ObjSet() param count ensures the result won't be negative: --param_count_excluding_rvalue; // Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best // to have it also block __Set. The code below is disabled to achieve this, with a slight cost to // performance when assigning to a new key in any object which has a base object. (The cost may // depend on how many key-value pairs each base object has.) Note that this doesn't affect meta- // functions defined in *this* base object, since they were already invoked if present. //if (IS_INVOKE_META) //{ // if (param_count_excluding_rvalue == 1) // // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to. // // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue. // param_count_excluding_rvalue = 0; // //else: Allow SET to operate on a field of an object stored in the target's base. // // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc. //} } - + if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0]))) - { // struct[] or struct[""] / obj[] := ptr + { // for struct[] and struct[""...] / struct[] := ptr and struct[""...] := ptr if (IS_INVOKE_SET) { if (TokenToObject(*aParam[param_count_excluding_rvalue])) { // Initialize structure using an object. e.g. struct[]:={x:1,y:2} this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue])); // return struct object aResultToken.symbol = SYM_OBJECT; aResultToken.object = this; this->AddRef(); return OK; } if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer { free(mStructMem); mMemAllocated = 0; } // assign new pointer to structure // releasing/deleting structure will not free that memory - mStructMem = (UINT_PTR *)TokenToInt64(*aParam[0]); + mStructMem = (UINT_PTR *)TokenToInt64(*aParam[param_count_excluding_rvalue]); } // Return new structure address aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64)mStructMem; return OK; } else { // Array access, struct.1 or struct[1] or struct[1].x ... if (TokenIsPureNumeric(*aParam[0])) { if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1])) { // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) // simply set pointer aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0])); else { // resolve pointer to pointer and set it - UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); + UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) - aResultToken.value_int64 = ((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1))); + aResultToken.value_int64 = ((mIsPointer ? *target : (UINT_PTR)target) + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1))); else { // resolve pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } aResultToken.symbol = SYM_INTEGER; return OK; } // Structure is a reference to variable and not a pointer, get size of structure if (mVarRef && !mIsPointer) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // Variable is a structure object, copy size if (TokenToObject(Var2)) ResultToken.value_int64 = ((Struct *)TokenToObject(Var2))->mSize; else { // use sizeof to find out the size of structure param[0]->symbol = SYM_STRING; Var1.marker = TokenToString(*param[1]); BIF_sizeof(Result,ResultToken,param,1); } } // Check if we have an array, if structure is not array and not pointer, assume array if (mArraySize || !mIsPointer) // if not Array and not pointer assume it is an array target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mIsPointer ? ptrsize : (mVarRef ? ResultToken.value_int64 : mSize/(mArraySize ? mArraySize : 1)))); else if (mIsPointer) // resolve pointer target = (UINT_PTR*)(*target + (TokenToInt64(*aParam[0])-1)*ptrsize); else // amend target to memory of field target = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mVarRef ? ResultToken.value_int64 : mSize)); // Structure has a variable reference and might be a pointer but not pointer to pointer if (mVarRef && mIsPointer < 2) { Var2.symbol = SYM_VAR; Var2.var = mVarRef; // variable is a structure object, clone it if (TokenToObject(Var2)) { objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target; if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } // Object to Structure if (IS_INVOKE_SET && TokenToObject(*aParam[1])) { objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // MULTIPARAM if (param_count_excluding_rvalue > 1) { objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; return OK; } else { Var1.symbol = SYM_STRING; Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = (UINT_PTR)target; if (objclone = Struct::Create(param,2)) { Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } tempobj->Release(); if (IS_INVOKE_SET && TokenToObject(*aParam[1])) { objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (param_count_excluding_rvalue > 1) { objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; return OK; } else return INVOKE_NOT_HANDLED; } } else { objclone = Clone(true); releaseobj = true; objclone->mStructMem = target; if (!mArraySize && mIsPointer) objclone->mIsPointer--; else if (mArraySize) { objclone->mArraySize = 0; objclone->mSize = mSize / mArraySize; } if (objclone->mIsPointer || (aParamCount == 1 && !mTypeOnly)) { if (param_count_excluding_rvalue > 1) { // MULTIPARAM objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); return OK; } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } else if (!mTypeOnly) { // the given integer is now excluded from parameters aParamCount--;param_count_excluding_rvalue--;aParam++; } } } if (mTypeOnly && !IS_INVOKE_CALL) // IS_INVOKE_CALL does not need the tentative field, it will handle it itself { - if (mVarRef) + if (mVarRef && !TokenIsEmptyString(*aParam[0])) { if (releaseobj) objclone->Release(); Var2.symbol = SYM_VAR; Var2.var = mVarRef; if (TokenToObject(Var2) && (objclone = ((Struct *)TokenToObject(Var2))->Clone(true))) { // variable is a structure object objclone->mStructMem = target; objclone->Invoke(aResultToken,ResultToken ,aFlags,aParam,aParamCount); objclone->Release(); return OK; } else { Var1.symbol = SYM_STRING; Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; - - // resolve pointer - Var2.value_int64 = mIsPointer ? *target : (UINT_PTR)target; - + Var2.value_int64 = 0; if (objclone = Struct::Create(param,2)) { // create structure from variable - Struct *tempobj = objclone->Clone(true); - tempobj->mStructMem = objclone->mStructMem; + Struct* tempobj = objclone->Clone(true); + // resolve pointer + tempobj->mStructMem = mIsPointer ? (UINT_PTR*)*target : target; tempobj->Invoke(aResultToken,aThisToken ,aFlags,aParam,aParamCount); tempobj->Release(); objclone->Release(); return OK; } return INVOKE_NOT_HANDLED; } } else // create field from structure { field = new FieldType(); deletefield = true; if (objclone == NULL) { // use this structure field->mMemAllocated = mMemAllocated; field->mIsInteger = mIsInteger; field->mIsPointer = mIsPointer; field->mEncoding = mEncoding; field->mIsUnsigned = mIsUnsigned; field->mOffset = 0; // structure with arrays so set to correct field size field->mSize = mSize / (mArraySize ? mArraySize : 1); field->mVarRef = 0; } else // use objclone created above { field->mMemAllocated = objclone->mMemAllocated; field->mIsInteger = objclone->mIsInteger; field->mIsPointer = objclone->mIsPointer; field->mEncoding = objclone->mEncoding; field->mIsUnsigned = objclone->mIsUnsigned; field->mOffset = 0; field->mSize = objclone->mSize / (objclone->mArraySize ? objclone->mArraySize : 1); } } } else if (!IS_INVOKE_CALL) // IS_INVOKE_CALL will handle the field itself field = FindField(TokenToString(*aParam[0])); } // // OPERATE ON A FIELD WITHIN THIS OBJECT // // CALL if (IS_INVOKE_CALL) { LPTSTR name = TokenToString(*aParam[0]); if (*name == '_') ++name; // ++ to exclude '_' from further consideration. ++aParam; --aParamCount; // Exclude the method identifier. A prior check ensures there was at least one param in this case. if (!_tcsicmp(name, _T("NewEnum"))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return _NewEnum(aResultToken, aParam, aParamCount); } // if first function parameter is a field get it if (!mTypeOnly && aParamCount && !TokenIsPureNumeric(*aParam[0])) { if (field = FindField(TokenToString(*aParam[0]))) { // exclude parameter in aParam ++aParam; --aParamCount; } } aResultToken.symbol = SYM_INTEGER; // mostly used aResultToken.value_int64 = 0; // set default if (!_tcsicmp(name, _T("SetCapacity"))) { // Set strcuture its capacity or fields capacity if (!field) { if (!aParamCount || !TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { // 0 or no parameters were given to free memory if (mMemAllocated > 0) { mMemAllocated = 0; free(mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mMemAllocated > 0) free(mStructMem); // allocate memory and zero-fill if (mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(mStructMem,NULL,(size_t)mMemAllocated); aResultToken.value_int64 = mMemAllocated; } else mMemAllocated = 0; } else if (aParamCount) { // we must have to parmeters here since first parameter is field - if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0])) + if (!TokenIsPureNumeric(*aParam[0]) || !TokenToInt64(*aParam[0]) || TokenToInt64(*aParam[0]) == 0) { if (field->mMemAllocated > 0) { field->mMemAllocated = 0; free(field->mStructMem); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // not numeric } if (field->mMemAllocated > 0) free(field->mStructMem); // allocate memory and zero-fill if (field->mStructMem = (UINT_PTR*)malloc((size_t)TokenToInt64(*aParam[0]))) { field->mMemAllocated = (int)TokenToInt64(*aParam[0]); memset(field->mStructMem,NULL,(size_t)field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; aResultToken.value_int64 = mMemAllocated; } else field->mMemAllocated = 0; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetCapacity"))) { if (field) aResultToken.value_int64 = field->mMemAllocated; else aResultToken.value_int64 = mMemAllocated; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Offset"))) { if (field) aResultToken.value_int64 = field->mOffset; else if (aParamCount && TokenIsPureNumeric(*aParam[0])) // calculate size if item is an array aResultToken.value_int64 = mSize / (mArraySize ? mArraySize : 1) * (TokenToInt64(*aParam[0])-1); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("IsPointer"))) { if (field) aResultToken.value_int64 = field->mIsPointer; else aResultToken.value_int64 = mIsPointer; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Encoding"))) { if (field) aResultToken.value_int64 = field->mEncoding == 65535 ? -1 : field->mEncoding; else aResultToken.value_int64 = mEncoding == 65535 ? -1 : mEncoding; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetPointer"))) { if (!field && aParamCount && mIsPointer) { // resolve array item if (mArraySize && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + ((mIsPointer ? ptrsize : (mSize/mArraySize)) * (TokenToInt64(*aParam[0])-1)))); else aResultToken.value_int64 = *target; } else if (field) aResultToken.value_int64 = *((UINT_PTR*)((UINT_PTR)target + field->mOffset)); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Fill"))) { if (!field) // only allow to fill main structure { if (aParamCount && TokenIsPureNumeric(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,TokenIsPureNumeric(*aParam[0]),mSize); else if (aParamCount && *TokenToString(*aParam[0])) memset(objclone ? objclone->mStructMem : mStructMem,*TokenToString(*aParam[0]),mSize); else memset(objclone ? objclone->mStructMem : mStructMem,NULL,mSize); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("GetAddress"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) aResultToken.value_int64 = (UINT_PTR)target + (mSize / mArraySize * (TokenToInt64(*aParam[0])-1)); else aResultToken.value_int64 = (UINT_PTR)target; } else aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Size"))) { if (!field) { if (mArraySize && aParamCount && TokenIsPureNumeric(*aParam[0])) // we do not care which item was requested because all are same size aResultToken.value_int64 = mSize / mArraySize; else aResultToken.value_int64 = mSize; } else aResultToken.value_int64 = field->mSize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("CountOf"))) { if (!field) aResultToken.value_int64 = mArraySize; else aResultToken.value_int64 = field->mArraySize; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (!_tcsicmp(name, _T("Clone")) || !_tcsicmp(name, _T("_New"))) { if (!field) { if (!releaseobj) // else we have a clone already objclone = this->Clone(); } else { Struct* tempobj = objclone; if (releaseobj) // release object, it is not requred anymore { objclone = objclone->CloneField(field); tempobj->Release(); } else objclone = this->CloneField(field); } if (aParamCount) { // structure pointer and / or init object were given if (TokenIsPureNumeric(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[0]); objclone->mMemAllocated = 0; if (aParamCount > 1 && TokenToObject(*aParam[1])) objclone->ObjectToStruct(TokenToObject(*aParam[1])); } else if (TokenToObject(*aParam[0])) { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); objclone->ObjectToStruct(TokenToObject(*aParam[0])); } } else { objclone->mStructMem = (UINT_PTR*)malloc(objclone->mSize); objclone->mMemAllocated = objclone->mSize; memset(objclone->mStructMem,NULL,objclone->mSize); } // small fix for _New to work properly because aThisToken contains the new object if (!_tcsicmp(name, _T("_New"))) { if (aThisToken.symbol == SYM_OBJECT) aThisToken.object->Release(); else aThisToken.symbol = SYM_OBJECT; aThisToken.object = objclone; objclone->AddRef(); } aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; if (deletefield) // we created the field from a structure delete field; // do not release objclone because it is returned return OK; } // For maintainability: explicitly return since above has done ++aParam, --aParamCount. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // identify that method was not found return INVOKE_NOT_HANDLED; } else if (!field) { // field was not found if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // MULTIPARAM[x,y] -- may be SET[x,y]:=z or GET[x,y], but always treated like GET[x]. else if (param_count_excluding_rvalue > 1) { // second parameter = "", so caller wants get/set field pointer if (TokenIsEmptyString(*aParam[1])) { aResultToken.symbol = SYM_INTEGER; if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) { // set simple pointer *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)TokenToInt64(*aParam[2]); - aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; + aResultToken.value_int64 = (UINT_PTR)*(target + field->mOffset); } else // set pointer to pointer { - UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + field->mOffset)); + UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) - aResultToken.value_int64 = (UINT_PTR)target + field->mOffset; + aResultToken.value_int64 = (mIsPointer ? *target : (UINT_PTR)target) + field->mOffset; else { // get pointer to pointer - UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + field->mOffset)); + UINT_PTR *aDeepPointer = ((UINT_PTR*)((mIsPointer ? *target : (UINT_PTR)target) + field->mOffset)); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // clone field to object and invoke again { if (releaseobj) objclone->Release(); objclone = CloneField(field,true); /* if (!field->mArraySize && field->mIsPointer) { objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); //objclone->mIsPointer--; if (--objclone->mIsPointer) // it is a pointer to array of pointers, set mArraySize to 1 to identify an array objclone->mArraySize = 1; } else objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[1])-1)*(field->mIsPointer ? ptrsize : field->mSize)); */ objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->Invoke(aResultToken,ResultToken,aFlags,aParam + 1,aParamCount - 1); objclone->Release(); if (deletefield) // we created the field from a structure delete field; return OK; } } // MULTIPARAM[x,y] x[y] // SET else if (IS_INVOKE_SET) { if (field->mVarRef && TokenToObject(*aParam[1])) { // field is a structure, assign objct to structure if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mStructMem = (UINT_PTR*)((UINT_PTR)target + field->mOffset); objclone->ObjectToStruct(TokenToObject(*aParam[1])); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer, clone to structure and invoke again if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); objclone->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); objclone->Release(); return OK; } // StrPut (code stolen from BIF_StrPut()) if (field->mEncoding != 65535) { // field is [T|W|U]CHAR or LP[TC]STR, set get character or string source_string = (LPCVOID)TokenToString(*aParam[1], aResultToken.buf); source_length = (int)((aParam[1]->symbol == SYM_VAR) ? aParam[1]->var->CharLength() : _tcslen((LPCTSTR)source_string)); if (field->mSize > 2) // not [T|W|U]CHAR source_length++; // for terminating character if (!source_length) { // Take a shortcut when source_string is empty, since some paths below might not handle it correctly. if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) // no memory allocated, don't allocate just return { aResultToken.value_int64 = 0; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mEncoding == CP_UTF16) *(LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; else *(LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)) = '\0'; aResultToken.value_int64 = 1; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } if (field->mSize > 2 && (!*((UINT_PTR*)((UINT_PTR)target + field->mOffset)) || (field->mMemAllocated > 0 && (field->mMemAllocated<(source_length*2))))) { // no memory allocated yet, allocate now if (field->mMemAllocated == -1 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))){ if (deletefield) // we created the field from a structure so no memory can be allocated delete field; if (releaseobj) objclone->Release(); return g_script.ScriptError(ERR_MUST_INIT_STRUCT); } else if (field->mMemAllocated > 0) // free previously allocated memory free(field->mStructMem); field->mMemAllocated = source_length * sizeof(TCHAR); field->mStructMem = (UINT_PTR*)malloc(field->mMemAllocated); *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)field->mStructMem; } if (field->mEncoding == UorA(CP_UTF16, CP_ACP)) tmemcpy((LPTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), (LPTSTR)source_string, field->mSize < 4 ? 1 : source_length); else { // Conversion is required. For Unicode builds, this means encoding != CP_UTF16; #ifndef UNICODE // therefore, this section is relevant only to ANSI builds: if (field->mEncoding == CP_UTF16) { // See similar section below for comments. char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, NULL, 0); if (!char_count) { aResultToken.value_int64 = char_count; if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). length = char_count; char_count = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)source_string, source_length, (LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length); if (field->mSize > 2 && char_count && char_count < length) ((LPWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)))[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 char_count = WideCharToMultiByte(field->mEncoding, WC_NO_BEST_FIT_CHARS, (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(field->mEncoding, flags, (LPCWSTR)source_string, source_length, NULL, 0, NULL, NULL); } if (!char_count) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } } if (field->mSize > 2) // Not TCHAR or CHAR or WCHAR ++char_count; // + 1 for null-terminator (source_length causes it to be excluded from char_count). // Assume there is sufficient buffer space and hope for the best: length = char_count; // Convert to target encoding. char_count = WideCharToMultiByte(field->mEncoding, flags, (LPCWSTR)source_string, source_length, (LPSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), char_count, 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 (field->mSize > 2 && char_count && char_count < length) // NOT TCHAR or CHAR or WCHAR ((LPSTR)((UINT_PTR)target + field->mOffset))[char_count++] = '\0'; #ifndef UNICODE } #endif } aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = char_count; } else { switch(field->mSize) { case 4: // Listed first for performance. if (field->mIsInteger) *((unsigned int *)((UINT_PTR)target + field->mOffset)) = (unsigned int)TokenToInt64(*aParam[1]); else // Float (32-bit). *((float *)((UINT_PTR)target + field->mOffset)) = (float)TokenToDouble(*aParam[1]); break; case 8: if (field->mIsInteger) // v1.0.48: Support unsigned 64-bit integers like DllCall does: *((__int64 *)((UINT_PTR)target + field->mOffset)) = (field->mIsUnsigned && !IS_NUMERIC(aParam[1]->symbol)) // Must not be numeric because those are already signed values, so should be written out as signed so that whoever uses them can interpret negatives as large unsigned values. ? (__int64)ATOU64(TokenToString(*aParam[1])) // For comments, search for ATOU64 in BIF_DllCall(). : TokenToInt64(*aParam[1]); else // Double (64-bit). *((double *)((UINT_PTR)target + field->mOffset)) = TokenToDouble(*aParam[1]); break; case 2: *((unsigned short *)((UINT_PTR)target + field->mOffset)) = (unsigned short)TokenToInt64(*aParam[1]); break; default: // size 1 *((unsigned char *)((UINT_PTR)target + field->mOffset)) = (unsigned char)TokenToInt64(*aParam[1]); } //*((int*)target + field->mOffset) = (int)TokenToInt64(*aParam[1]); aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = TokenToInt64(*aParam[1]); } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } // GET else if (field) { if (field->mArraySize || field->mVarRef) { // filed is an array or variable reference, return a structure object. if (field->mArraySize || field->mIsPointer) { // field is array or a pointer to variable objclone = CloneField(field,true); objclone->mStructMem = (UINT_PTR *)((UINT_PTR)target + field->mOffset); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } else // field is refference to a variable and not pointer, create structure { Var1.symbol = SYM_STRING; Var2.symbol = SYM_VAR; Var2.var = field->mVarRef; if (TokenToObject(Var2)) { // Variable is a structure object objclone = ((Struct *)TokenToObject(Var2))->Clone(true); objclone->mStructMem = target + field->mOffset; aResultToken.object = objclone; aResultToken.symbol = SYM_OBJECT; } else // Variable is a string definition { Var1.marker = TokenToString(Var2); Var2.symbol = SYM_INTEGER; Var2.value_int64 = field->mIsPointer ? *(UINT_PTR*)((UINT_PTR)target + field->mOffset) : (UINT_PTR)((UINT_PTR)target + field->mOffset); if (objclone = Struct::Create(param,2)) { // create and clone object because it is created dynamically Struct *tempobj = objclone; objclone = objclone->Clone(true); objclone->mStructMem = tempobj->mStructMem; tempobj->Release(); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; } } } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (mIsPointer && objclone == NULL) { // resolve pointer of main structure for (int i = mIsPointer;i;i--) target = (UINT_PTR*)*target; } else if (objclone && objclone->mIsPointer) { // resolve pointer for objclone for (int i = objclone->mIsPointer;i;i--) target = (UINT_PTR*)*target; } if (field->mIsPointer) { // field is a pointer we need to return an object if (releaseobj) objclone->Release(); objclone = this->CloneField(field,true); objclone->mIsPointer--; objclone->mStructMem = (UINT_PTR*)*((UINT_PTR*)((UINT_PTR)target + field->mOffset)); aResultToken.symbol = SYM_OBJECT; aResultToken.object = objclone; return OK; } // StrGet (code stolen from BIF_StrGet()) if (field->mEncoding != 65535) { if (field->mEncoding != UorA(CP_UTF16, CP_ACP)) { // Conversion is required. int conv_length; if (field->mSize < 4) // TCHAR or CHAR or WCHAR length = 1; #ifdef UNICODE // Convert multi-byte encoded string to UTF-16. conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } conv_length = MultiByteToWideChar(field->mEncoding, 0, (LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length); #else CStringW wide_buf; // If the target string is not UTF-16, convert it to that first. if (field->mEncoding != CP_UTF16) { StringCharToWChar((LPCSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), wide_buf, length, field->mEncoding); (field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : *(UINT_PTR*)((UINT_PTR)target + field->mOffset)) = (UINT_PTR)wide_buf.GetString(); length = wide_buf.GetLength(); } // Now convert UTF-16 to ACP. conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, NULL, 0, NULL, NULL); if (!TokenSetResult(aResultToken, NULL, conv_length)) // DO NOT SUBTRACT 1, conv_length might not include a null-terminator. { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; // Out of memory. } conv_length = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, (LPCWSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)), length, aResultToken.marker, conv_length, NULL, NULL); #endif if (conv_length && !aResultToken.marker[conv_length - 1]) --conv_length; // Exclude null-terminator. else aResultToken.marker[conv_length] = '\0'; aResultToken.marker_length = conv_length; // Update this in case TokenSetResult used mem_to_free. if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } else // no conversation required { if (field->mSize > 2 && !*((UINT_PTR*)((UINT_PTR)target + field->mOffset))) { if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } aResultToken.symbol = SYM_STRING; if (!TokenSetResult(aResultToken, (LPCTSTR)(field->mSize > 2 ? *((UINT_PTR*)((UINT_PTR)target + field->mOffset)) : ((UINT_PTR)target + field->mOffset)),field->mSize < 4 ? 1 : -1)) aResultToken.marker = _T(""); } aResultToken.symbol = SYM_STRING; } - else + else // NumGet (code stolen from BIF_NumGet()) { switch(field->mSize) { case 4: // Listed first for performance. if (!field->mIsInteger) aResultToken.value_double = *((float *)((UINT_PTR)target + field->mOffset)); else if (!field->mIsUnsigned) aResultToken.value_int64 = *((int *)((UINT_PTR)target + field->mOffset)); // aResultToken.symbol was set to SYM_FLOAT or SYM_INTEGER higher above. else aResultToken.value_int64 = *((unsigned int *)((UINT_PTR)target + field->mOffset)); break; case 8: // The below correctly copies both DOUBLE and INT64 into the union. // Unsigned 64-bit integers aren't supported because variables/expressions can't support them. aResultToken.value_int64 = *((__int64 *)((UINT_PTR)target + field->mOffset)); break; case 2: if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((short *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned short *)((UINT_PTR)target + field->mOffset)); break; default: // size 1 if (!field->mIsUnsigned) // Don't use ternary because that messes up type-casting. aResultToken.value_int64 = *((char *)((UINT_PTR)target + field->mOffset)); else aResultToken.value_int64 = *((unsigned char *)((UINT_PTR)target + field->mOffset)); } aResultToken.symbol = SYM_INTEGER; } if (deletefield) // we created the field from a structure delete field; if (releaseobj) objclone->Release(); return OK; } if (releaseobj) objclone->Release(); return INVOKE_NOT_HANDLED; } // // Struct:: Internal Methods // Struct::FieldType *Struct::FindField(LPTSTR val) { for (int i = 0;i < mFieldCount;i++) { FieldType &field = mFields[i]; if (!_tcsicmp(field.key,val)) return &field; } return NULL; } bool Struct::SetInternalCapacity(IndexType new_capacity) // Expands mFields to the specified number if fields. // Caller *must* ensure new_capacity >= 1 && new_capacity >= mFieldCount. { FieldType *new_fields = (FieldType *)realloc(mFields, new_capacity * sizeof(FieldType)); if (!new_fields) return false; mFields = new_fields; mFieldCountMax = new_capacity; return true; } ResultType Struct::_NewEnum(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { if (aParamCount == 0) { IObject *newenum; if (newenum = new Enumerator(this)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = newenum; } } return OK; } int Struct::Enumerator::Next(Var *aKey, Var *aVal) { if (++mOffset < mObject->mFieldCount) { FieldType &field = mObject->mFields[mOffset]; if (aKey) aKey->Assign(field.key); if (aVal) { // We need to invoke the structure to retrieve the value ExprTokenType aResultToken; // not sure about the buffer TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } else if (mOffset < mObject->mArraySize) { // structure is an array if (aKey) aKey->Assign(mOffset + 1); // mOffset starts at 1 if (aVal) { // again we need to invoke structure to retrieve the value ExprTokenType aResultToken; TCHAR buf[MAX_PATH]; aResultToken.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = mObject; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_INTEGER; aVarToken->value_int64 = mOffset + 1; // mOffset starts at 1 mObject->Invoke(aResultToken,aThisToken,0,&aVarToken,1); switch (aResultToken.symbol) { case SYM_STRING: aVal->AssignString(aResultToken.marker); break; case SYM_INTEGER: aVal->Assign(aResultToken.value_int64); break; case SYM_FLOAT: aVal->Assign(aResultToken.value_double); break; case SYM_OBJECT: aVal->Assign(aResultToken.object); break; } delete aVarToken; } return true; } return false; } Struct::FieldType *Struct::Insert(LPTSTR key, IndexType at,UCHAR aIspointer,int aOffset,int aArrsize,Var *variableref,int aFieldsize,bool aIsinteger,bool aIsunsigned,USHORT aEncoding) // Inserts a single field with the given key at the given offset. // Caller must ensure 'at' is the correct offset for this key. { if (!*key) { // empty key = only type was given so assign all to structure object // do not assign size here since it will be assigned in StructCreate later mArraySize = aArrsize; mIsPointer = aIspointer; mIsInteger = aIsinteger; mIsUnsigned = aIsunsigned; mEncoding = aEncoding; mVarRef = variableref; return (FieldType*)true; } if (mFieldCount == mFieldCountMax && !Expand() // Attempt to expand if at capacity. || !(key = _tcsdup(key))) // Attempt to duplicate key-string. { // Out of memory. return NULL; } // There is now definitely room in mFields for a new field. FieldType &field = mFields[at]; if (at < mFieldCount) // Move existing fields to make room. memmove(&field + 1, &field, (mFieldCount - at) * sizeof(FieldType)); ++mFieldCount; // Only after memmove above. // Update key-type offsets based on where and what was inserted; also update this key's ref count: field.mSize = aFieldsize; // Init to ensure safe behaviour in Assign(). field.key = key; // Above has already copied string field.mArraySize = aArrsize; field.mIsPointer = aIspointer; field.mOffset = aOffset; field.mIsInteger = aIsinteger; field.mIsUnsigned = aIsunsigned; field.mEncoding = aEncoding; field.mVarRef = variableref; field.mMemAllocated = 0; return &field; } #ifdef CONFIG_DEBUGGER void Struct::DebugWriteProperty(IDebugProperties *aDebugger, int aPage, int aPageSize, int aDepth) { DebugCookie cookie; aDebugger->BeginProperty(NULL, "object", (int)mFieldCount, cookie); if (aDepth) { int i = aPageSize * aPage, j = aPageSize * (aPage + 1); if (j > (int)mFieldCount) j = (int)mFieldCount; // For each field in the requested page... for ( ; i < j; ++i) { Struct::FieldType &field = mFields[i]; ExprTokenType value; TCHAR buf[MAX_PATH]; value.buf = buf; ExprTokenType aThisToken; aThisToken.symbol = SYM_OBJECT; aThisToken.object = this; ExprTokenType *aVarToken = new ExprTokenType(); aVarToken->symbol = SYM_STRING; aVarToken->marker = field.key; this->Invoke(value,aThisToken,0,&aVarToken,1); delete aVarToken; if (field.mEncoding != 65535) // String aDebugger->WriteProperty(CStringUTF8FromTChar(field.key), value); } } aDebugger->EndProperty(cookie); } #endif
tinku99/ahkdll
c1e5b6793a993866430af05a95fa0cba71d52b98
Fixed A_ThisFunc was not restored correctly for static structures
diff --git a/source/script_struct.cpp b/source/script_struct.cpp index 229c244..f33c8dc 100644 --- a/source/script_struct.cpp +++ b/source/script_struct.cpp @@ -1,802 +1,797 @@ #include "stdafx.h" // pre-compiled headers #include "defines.h" #include "application.h" #include "globaldata.h" #include "script.h" #include "TextIO.h" #include "script_object.h" // // Struct::Create - Called by BIF_ObjCreate to create a new object, optionally passing key/value pairs to set. // Struct *Struct::Create(ExprTokenType *aParam[], int aParamCount) // This code is very similar to BIF_sizeof so should be maintained together { int ptrsize = sizeof(UINT_PTR); // Used for pointers on 32/64 bit system int offset = 0; // also used to calculate total size of structure int arraydef = 0; // count arraysize to update offset int unionoffset[100]; // backup offset before we enter union or structure int unionsize[100]; // calculate unionsize bool unionisstruct[100]; // updated to move offset for structure in structure int totalunionsize = 0; // total size of all unions and structures in structure int uniondepth = 0; // count how deep we are in union/structure int ispointer = NULL; // identify pointer and how deep it goes #ifdef _WIN64 int aligntotal = 0; // pointer alignment for total structure #endif int thissize; // used to check if type was found in above array. // following are used to find variable and also get size of a structure defined in variable // this will hold the variable reference and offset that is given to size() to align if necessary in 64-bit ResultType Result = OK; ExprTokenType ResultToken; ExprTokenType Var1,Var2,Var3; ExprTokenType *param[] = {&Var1,&Var2,&Var3}; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; // will hold pointer to structure definition string while we parse trough it TCHAR *buf; size_t buf_size; // Use enough buffer to accept any definition in a field. TCHAR tempbuf[LINE_SIZE]; // just in case if we have a long comment // definition and field name are same max size as variables // also add enough room to store pointers (**) and arrays [1000] TCHAR defbuf[MAX_VAR_NAME_LENGTH*2 + 40]; // give more room to use local or static variable Function(variable) TCHAR keybuf[MAX_VAR_NAME_LENGTH + 40]; // buffer for arraysize + 2 for bracket ] and terminating character TCHAR intbuf[MAX_INTEGER_LENGTH + 2]; FieldType *field; // used to define a field // Structure object is saved in fixed order // insert_pos is simply increased each time // for loop will enumerate items in same order as it was created IndexType insert_pos = 0; // the new structure object Struct *obj = new Struct(); // Parameter passed to IsDefaultType needs to be ' Definition ' // this is because spaces are used as delimiters ( see IsDefaultType function ) // So first character will be always a space defbuf[0] = ' '; if (TokenToObject(*aParam[0])) { obj->Release(); obj = ((Struct *)TokenToObject(*aParam[0]))->Clone(); if (aParamCount > 2) { obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); obj->ObjectToStruct(TokenToObject(*aParam[2])); } else if (aParamCount > 1) { if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,offset); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)TokenToInt64(*aParam[1]); } else { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); } return obj; } // Set initial capacity to avoid multiple expansions. // For simplicity, failure is handled by the loop below. obj->SetInternalCapacity(aParamCount >> 1); // Set buf to beginning of structure definition buf = TokenToString(*aParam[0]); // continue as long as we did not reach end of string / structure definition while (*buf) { if (!_tcsncmp(buf,_T("//"),2)) // exclude comments { buf = StrChrAny(buf,_T("\n\r")) ? StrChrAny(buf,_T("\n\r")) : (buf + _tcslen(buf)); if (!*buf) break; // end of definition reached } if (buf == StrChrAny(buf,_T("\n\r\t "))) { // Ignore spaces, tabs and new lines before field definition buf++; continue; } else if (_tcschr(buf,'{') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'{') < StrChrAny(buf, _T(";,")))) { // union or structure in structure definition if (!uniondepth++) totalunionsize = 0; // done here to reduce code if (_tcsstr(buf,_T("struct")) && _tcsstr(buf,_T("struct")) < _tcschr(buf,'{')) unionisstruct[uniondepth] = true; // mark that union is a structure else unionisstruct[uniondepth] = false; // backup offset because we need to set it back after this union / struct was parsed // unionsize is initialized to 0 and buffer moved to next character unionoffset[uniondepth] = offset; // backup offset unionsize[uniondepth] = 0; // ignore even any wrong input here so it is even {mystructure...} for struct and {anyother string...} for union buf = _tcschr(buf,'{') + 1; continue; } else if (*buf == '}') { // update union // restore offset even if we had a structure in structure if (unionsize[uniondepth]>totalunionsize) totalunionsize = unionsize[uniondepth]; // last item in union or structure, update offset now if not struct, for struct offset is up to date if (--uniondepth == 0) { if (!unionisstruct[uniondepth + 1]) // because it was decreased above offset += totalunionsize; } else offset = unionoffset[uniondepth]; buf++; if (buf == StrChrAny(buf,_T(";,"))) buf++; continue; } // set defaults ispointer = false; arraydef = 0; // copy current definition field to temporary buffer if (StrChrAny(buf, _T("};,"))) { if ((buf_size = _tcscspn(buf, _T("};,"))) > LINE_SIZE - 1) { obj->Release(); return NULL; } _tcsncpy(tempbuf,buf,buf_size); tempbuf[buf_size] = '\0'; } else if (_tcslen(buf) > LINE_SIZE - 1) { obj->Release(); return NULL; } else _tcscpy(tempbuf,buf); // Trim trailing spaces rtrim(tempbuf); // Pointer if (_tcschr(tempbuf,'*')) ispointer = StrReplace(tempbuf, _T("*"), _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Array if (_tcschr(tempbuf,'[')) { _tcsncpy(intbuf,_tcschr(tempbuf,'['),MAX_INTEGER_LENGTH); intbuf[_tcscspn(intbuf,_T("]")) + 1] = '\0'; arraydef = (int)ATOI64(intbuf + 1); // remove array definition from temp buffer to identify key easier StrReplace(tempbuf, intbuf, _T(""), SCS_SENSITIVE, UINT_MAX, LINE_SIZE); // Trim trailing spaces in case we had a definition like UInt [10] rtrim(tempbuf); } // copy type // if offset is 0 and there are no };, characters, it means we have a pure definition if (StrChrAny(tempbuf, _T(" \t")) || StrChrAny(tempbuf,_T("};,")) || (!StrChrAny(buf,_T("};,")) && !offset)) { if ((buf_size = _tcscspn(tempbuf,_T("\t "))) > MAX_VAR_NAME_LENGTH*2 + 30) { obj->Release(); return NULL; } _tcsncpy(defbuf + 1,tempbuf,buf_size); //_tcscpy(defbuf + 1 + _tcscspn(tempbuf,_T("\t ")),_T(" ")); defbuf[1 + buf_size] = ' '; defbuf[2 + buf_size] = '\0'; if (StrChrAny(tempbuf, _T(" \t"))) { if (_tcslen(StrChrAny(tempbuf, _T(" \t"))) > MAX_VAR_NAME_LENGTH + 30) { obj->Release(); return NULL; } _tcscpy(keybuf,StrChrAny(tempbuf, _T(" \t")) + 1); ltrim(keybuf); } else keybuf[0] = '\0'; } else // Not 'TypeOnly' definition because there are more than one fields in array so use default type UInt { _tcscpy(defbuf,_T(" UInt ")); _tcscpy(keybuf,tempbuf); } // Now find size in default types array and create new field // If Type not found, resolve type to variable and get size of struct defined in it if ((thissize = IsDefaultType(defbuf))) { if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,NULL,ispointer ? ptrsize : thissize ,ispointer ? true : !tcscasestr(_T(" FLOAT DOUBLE PFLOAT PDOUBLE "),defbuf) ,!tcscasestr(_T(" PTR SHORT INT INT64 CHAR VOID HALF_PTR BOOL INT32 LONG LONG32 LONGLONG LONG64 USN INT_PTR LONG_PTR POINTER_64 POINTER_SIGNED SSIZE_T WPARAM __int64 "),defbuf) ,tcscasestr(_T(" TCHAR LPTSTR LPCTSTR LPWSTR LPCWSTR WCHAR "),defbuf) ? 1200 : tcscasestr(_T(" CHAR LPSTR LPCSTR LPSTR UCHAR "),defbuf) ? 0 : -1))) { // Out of memory. obj->Release(); return NULL; } offset += (ispointer ? ptrsize : thissize) * (arraydef ? arraydef : 1); #ifdef _WIN64 // align offset for pointer if (ispointer) { if (offset % ptrsize) offset += (ptrsize - (offset % ptrsize)) * (arraydef ? arraydef : 1); if (ptrsize > aligntotal) aligntotal = ptrsize; } else { if (offset % thissize) offset += thissize - (offset % thissize); if (thissize > aligntotal) aligntotal = thissize; } #endif } else // type was not found, check for user defined type in variables { Var1.var = NULL; // init to not found Func *bkpfunc = NULL; // check if we have a local/static declaration and resolve to function // For example Struct("*MyFunc(mystruct) mystr") if (_tcschr(defbuf,'(')) { bkpfunc = g->CurrentFunc; // don't bother checking, just backup and restore later g->CurrentFunc = g_script.FindFunc(defbuf + 1,_tcscspn(defbuf,_T("(")) - 1); if (g->CurrentFunc) // break if not found to identify error { _tcscpy(tempbuf,defbuf + 1); _tcscpy(defbuf + 1,tempbuf + _tcscspn(tempbuf,_T("(")) + 1); //,_tcschr(tempbuf,')') - _tcschr(tempbuf,'(')); _tcscpy(_tcschr(defbuf,')'),_T(" \0")); + Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); + g->CurrentFunc = bkpfunc; } else // release object and return { - if (bkpfunc) - g->CurrentFunc = bkpfunc; + g->CurrentFunc = bkpfunc; obj->Release(); return NULL; } } - // try to find local variable first - if (g->CurrentFunc) - { + else if (g->CurrentFunc) // try to find local variable first Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_LOCAL,NULL); - // only restore here because otherwise no function - if (bkpfunc) - g->CurrentFunc = bkpfunc; - } // try to find global variable if local was not found or we are not in func if (Var1.var == NULL) Var1.var = g_script.FindVar(defbuf + 1,_tcslen(defbuf) - 2,NULL,FINDVAR_GLOBAL,NULL); // variable found if (Var1.var != NULL) { if (!ispointer && !_tcsncmp(tempbuf,buf,_tcslen(buf)) && !*keybuf) { // Whole definition is not a pointer and no key was given so create Structure from variable obj->Release(); if (aParamCount == 1) { if (TokenToObject(*param[0])) { // assume variable is a structure object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); return obj; } // else create structure from string definition return Struct::Create(param,1); } else if (aParamCount > 1) { // more than one parameter was given, copy aParam to param param[1]->symbol = aParam[1]->symbol; param[1]->object = aParam[1]->object; param[1]->value_int64 = aParam[1]->value_int64; param[1]->var = aParam[1]->var; } if (aParamCount > 2) { // more than 2 parameters were given, copy aParam to param param[2]->symbol = aParam[2]->symbol; param[2]->object = aParam[2]->object; param[2]->var = aParam[2]->var; // definition variable is a structure object, clone it, assign memory and init object if (TokenToObject(*param[0])) { obj = ((Struct *)TokenToObject(*param[0]))->Clone(); obj->mMemAllocated = 0; obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; obj->ObjectToStruct(TokenToObject(*aParam[2])); return obj; } return Struct::Create(param,3); } else if (TokenToObject(*param[0])) { // definition variable is a structure object, clone it and assign memory or init object obj = ((Struct *)TokenToObject(*param[0]))->Clone(); if (TokenToObject(*aParam[1])) { obj->mStructMem = (UINT_PTR *)malloc(obj->mSize); obj->mMemAllocated = obj->mSize; memset(obj->mStructMem,NULL,obj->mSize); obj->ObjectToStruct(TokenToObject(*aParam[1])); } else obj->mStructMem = (UINT_PTR*)aParam[1]->value_int64; return obj; } // else simply create structure from variable and given memory/initobject return Struct::Create(param,2); } // Call BIF_sizeof passing offset in second parameter to align offset if necessary // if field is a pointer we will need its size only param[1]->value_int64 = (__int64)ispointer ? 0 : offset; BIF_sizeof(Result,ResultToken,param,ispointer ? 1 : 2); if (ResultToken.symbol != SYM_INTEGER) { // could not resolve structure obj->Release(); return NULL; } // Insert new field in our structure if (!(field = obj->Insert(keybuf, insert_pos++,ispointer,offset,arraydef,Var1.var,ispointer ? 4 : (int)ResultToken.value_int64,1,1,-1))) { // Out of memory. obj->Release(); return NULL; } if (ispointer) offset += (int)(ispointer ? ptrsize : ResultToken.value_int64) * (arraydef ? arraydef : 1); else // sizeof was given an offset that it applied and aligned if necessary, so set offset = and not += offset = (int)(ispointer ? ptrsize : ResultToken.value_int64) * (arraydef ? arraydef : 1); #ifdef _WIN64 // align offset for pointer if (ispointer) { if (offset % ptrsize) offset += ptrsize - (offset % ptrsize); } #endif } else // No variable was found and it is not default type so we can't determine size. { obj->Release(); return NULL; } } // update union size if (uniondepth) { if ((offset - unionoffset[uniondepth]) > unionsize[uniondepth]) unionsize[uniondepth] = offset - unionoffset[uniondepth]; // reset offset if in union and union is not a structure if (!unionisstruct[uniondepth]) offset = unionoffset[uniondepth]; } // Move buffer pointer now if (_tcschr(buf,'}') && (!StrChrAny(buf, _T(";,")) || _tcschr(buf,'}') < StrChrAny(buf, _T(";,")))) buf += _tcscspn(buf,_T("}")); // keep } character to update union else if (StrChrAny(buf, _T(";,"))) buf += _tcscspn(buf,_T(";,")) + 1; else { // identify that structure object has no fields if (!*keybuf) obj->mTypeOnly = true; buf += _tcslen(buf); } } #ifdef _WIN64 // align total structure if necessary if (aligntotal) offset += offset % aligntotal; #endif if (!offset) // structure could not be build { obj->Release(); return NULL; } obj->mSize = offset; if (aParamCount > 1 && TokenIsPureNumeric(*aParam[1])) { // second parameter exist and it is digit assumme this is new pointer for our structure obj->mStructMem = (UINT_PTR *)TokenToInt64(*aParam[1]); obj->mMemAllocated = 0; } else // no pointer given so allocate memory and fill memory with 0 { // setting the memory after parsing definition saves a call to BIF_sizeof obj->mStructMem = (UINT_PTR *)malloc(offset); obj->mMemAllocated = offset; memset(obj->mStructMem,NULL,offset); } // an object was passed to initialize fields // enumerate trough object and assign values if ((aParamCount > 1 && !TokenIsPureNumeric(*aParam[1])) || aParamCount > 2 ) obj->ObjectToStruct(TokenToObject(aParamCount == 2 ? *aParam[1] : *aParam[2])); return obj; } // // Struct::ObjectToStruct - Initialize structure from array, object or structure. // void Struct::ObjectToStruct(IObject *objfrom) { ExprTokenType ResultToken, this_token,enum_token,param_tokens[3]; ExprTokenType *params[] = { param_tokens, param_tokens+1, param_tokens+2 }; TCHAR defbuf[MAX_PATH],buf[MAX_PATH]; int param_count = 3; // Set up enum_token the way Invoke expects: enum_token.symbol = SYM_STRING; enum_token.marker = _T(""); enum_token.mem_to_free = NULL; enum_token.buf = defbuf; // Prepare to call object._NewEnum(): param_tokens[0].symbol = SYM_STRING; param_tokens[0].marker = _T("_NewEnum"); objfrom->Invoke(enum_token, ResultToken, IT_CALL, params, 1); if (enum_token.mem_to_free) // Invoke returned memory for us to free. free(enum_token.mem_to_free); // Check if object returned an enumerator, otherwise return if (enum_token.symbol != SYM_OBJECT) return; // create variables to use in for loop / for enumeration // these will be deleted afterwards Var *var1 = (Var*)alloca(sizeof(Var)); Var *var2 = (Var*)alloca(sizeof(Var)); var1->mType = var2->mType = VAR_NORMAL; var1->mAttrib = var2->mAttrib = 0; var1->mByteCapacity = var2->mByteCapacity = 0; var1->mHowAllocated = var2->mHowAllocated = ALLOC_MALLOC; // Prepare parameters for the loop below: enum.Next(var1 [, var2]) param_tokens[0].marker = _T("Next"); param_tokens[1].symbol = SYM_VAR; param_tokens[1].var = var1; param_tokens[1].mem_to_free = 0; param_tokens[2].symbol = SYM_VAR; param_tokens[2].var = var2; param_tokens[2].mem_to_free = 0; ExprTokenType result_token; IObject &enumerator = *enum_token.object; // Might perform better as a reference? this_token.symbol = SYM_OBJECT; this_token.object = this; for (;;) { // Set up result_token the way Invoke expects; each Invoke() will change some or all of these: result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; // Call enumerator.Next(var1, var2) enumerator.Invoke(result_token,enum_token,IT_CALL, params, param_count); bool next_returned_true = TokenToBOOL(result_token, TokenIsPureNumeric(result_token)); if (!next_returned_true) break; this->Invoke(ResultToken,this_token,IT_SET,params+1,2); // release object if it was assigned prevoiously when calling enum.Next if (var1->IsObject()) var1->ReleaseObject(); if (var2->IsObject()) var2->ReleaseObject(); // Free any memory or object which may have been returned by Invoke: if (result_token.mem_to_free) free(result_token.mem_to_free); if (result_token.symbol == SYM_OBJECT) result_token.object->Release(); } // release enumerator and free vars enumerator.Release(); var1->Free(); var2->Free(); } // // Struct::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool Struct::Delete() { return ObjectBase::Delete(); } Struct::~Struct() { if (mMemAllocated > 0) free(mStructMem); if (mFields) { if (mFieldCount) { IndexType i = mFieldCount - 1; // Free keys for ( ; i >= 0 ; --i) { if (mFields[i].mMemAllocated > 0) free(mFields[i].mStructMem); free(mFields[i].key); } } // Free fields array. free(mFields); } } // // Struct::SetPointer - used to set pointer for a field or array item // UINT_PTR Struct::SetPointer(UINT_PTR aPointer,int aArrayItem) { *((UINT_PTR*)((UINT_PTR)mStructMem + (aArrayItem-1)*(mSize/(mArraySize ? mArraySize : 1)))) = aPointer; return aPointer; } // // Struct::FieldType::Clone - used to clone a field to structure. // Struct *Struct::CloneField(FieldType *field,bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; // if field is an array, set correct size if (obj.mArraySize = field->mArraySize) obj.mSize = field->mSize*obj.mArraySize; else obj.mSize = field->mSize; obj.mIsInteger = field->mIsInteger; obj.mIsPointer = field->mIsPointer; obj.mEncoding = field->mEncoding; obj.mIsUnsigned = field->mIsUnsigned; obj.mVarRef = field->mVarRef; obj.mTypeOnly = 1; obj.mMemAllocated = aIsDynamic ? -1 : 0; return objptr; } // // Struct::Clone - used for cloning structures. // Struct *Struct::Clone(bool aIsDynamic) // Creates an object and copies to it the fields at and after the given offset. { Struct *objptr = new Struct(); if (!objptr) return objptr; Struct &obj = *objptr; obj.mArraySize = mArraySize; obj.mIsInteger = mIsInteger; obj.mIsPointer = mIsPointer; obj.mEncoding = mEncoding; obj.mIsUnsigned = mIsUnsigned; obj.mSize = mSize; obj.mVarRef = mVarRef; obj.mTypeOnly = mTypeOnly; // -1 will identify a dynamic structure, no memory can be allocated to such obj.mMemAllocated = aIsDynamic ? -1 : 0; // Allocate space in destination object. if (!obj.SetInternalCapacity(mFieldCount)) { obj.Release(); return NULL; } FieldType *fields = obj.mFields; // Newly allocated by above. int failure_count = 0; // See comment below. IndexType i; obj.mFieldCount = mFieldCount; for (i = 0; i < mFieldCount; ++i) { FieldType &dst = fields[i]; FieldType &src = mFields[i]; if ( !(dst.key = _tcsdup(src.key)) ) { // Key allocation failed. // Rather than trying to set up the object so that what we have // so far is valid in order to break out of the loop, continue, // make all fields valid and then allow them to be freed. ++failure_count; } dst.mArraySize = src.mArraySize; dst.mIsInteger = src.mIsInteger; dst.mIsPointer = src.mIsPointer; dst.mEncoding = src.mEncoding; dst.mIsUnsigned = src.mIsUnsigned; dst.mOffset = src.mOffset; dst.mSize = src.mSize; dst.mVarRef = src.mVarRef; dst.mMemAllocated = aIsDynamic ? -1 : 0; } if (failure_count) { // One or more memory allocations failed. It seems best to return a clear failure // indication rather than an incomplete copy. Now that the loop above has finished, // the object's contents are at least valid and it is safe to free the object: obj.Release(); return NULL; } return &obj; } // // Struct::Invoke - Called by BIF_ObjInvoke when script explicitly interacts with an object. // ResultType STDMETHODCALLTYPE Struct::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) // L40: Revised base mechanism for flexibility and to simplify some aspects. // obj[] -> obj.base.__Get -> obj.base[] -> obj.base.__Get etc. { int ptrsize = sizeof(UINT_PTR); FieldType *field = NULL; // init to NULL to use in IS_INVOKE_CALL ResultType Result = OK; // Used to resolve dynamic structures ExprTokenType Var1,Var2; Var1.symbol = SYM_VAR; Var2.symbol = SYM_INTEGER; ExprTokenType *param[] = {&Var1,&Var2},ResultToken; // used to clone a dynamic field or structure Struct *objclone = NULL; // used for StrGet/StrPut LPCVOID source_string; int source_length; DWORD flags = WC_NO_BEST_FIT_CHARS; int length = -1; int char_count; // Identify that we need to release/delete field or structure object bool deletefield = false; bool releaseobj = false; int param_count_excluding_rvalue = aParamCount; // target may be altered here to resolve dynamic structure so hold it separately UINT_PTR *target = mStructMem; if (IS_INVOKE_SET) { // Prior validation of ObjSet() param count ensures the result won't be negative: --param_count_excluding_rvalue; // Since defining base[key] prevents base.base.__Get and __Call from being invoked, it seems best // to have it also block __Set. The code below is disabled to achieve this, with a slight cost to // performance when assigning to a new key in any object which has a base object. (The cost may // depend on how many key-value pairs each base object has.) Note that this doesn't affect meta- // functions defined in *this* base object, since they were already invoked if present. //if (IS_INVOKE_META) //{ // if (param_count_excluding_rvalue == 1) // // Prevent below from unnecessarily searching for a field, since it won't actually be assigned to. // // Relies on mBase->Invoke recursion using aParamCount and not param_count_excluding_rvalue. // param_count_excluding_rvalue = 0; // //else: Allow SET to operate on a field of an object stored in the target's base. // // For instance, x[y,z]:=w may operate on x[y][z], x.base[y][z], x[y].base[z], etc. //} } if (!param_count_excluding_rvalue || (param_count_excluding_rvalue == 1 && TokenIsEmptyString(*aParam[0]))) { // struct[] or struct[""] / obj[] := ptr if (IS_INVOKE_SET) { if (TokenToObject(*aParam[param_count_excluding_rvalue])) { // Initialize structure using an object. e.g. struct[]:={x:1,y:2} this->ObjectToStruct(TokenToObject(*aParam[param_count_excluding_rvalue])); // return struct object aResultToken.symbol = SYM_OBJECT; aResultToken.object = this; this->AddRef(); return OK; } if (mMemAllocated > 0) // free allocated memory because we will assign a custom pointer { free(mStructMem); mMemAllocated = 0; } // assign new pointer to structure // releasing/deleting structure will not free that memory mStructMem = (UINT_PTR *)TokenToInt64(*aParam[0]); } // Return new structure address aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64)mStructMem; return OK; } else { // Array access, struct.1 or struct[1] or struct[1].x ... if (TokenIsPureNumeric(*aParam[0])) { if (param_count_excluding_rvalue > 1 && TokenIsEmptyString(*aParam[1])) { // caller wants set/get pointer. E.g. struct.2[""] or struct.2[""] := ptr if (IS_INVOKE_SET) { if (param_count_excluding_rvalue < 3) // simply set pointer aResultToken.value_int64 = SetPointer((UINT_PTR)TokenToInt64(*aParam[2]),(int)TokenToInt64(*aParam[0])); else { // resolve pointer to pointer and set it UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; *aDeepPointer = (UINT_PTR)TokenToInt64(*aParam[aParamCount]); aResultToken.value_int64 = *aDeepPointer; } } else // GET pointer { if (param_count_excluding_rvalue < 3) aResultToken.value_int64 = ((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize / (mArraySize ? mArraySize : 1))); else { // resolve pointer to pointer UINT_PTR *aDeepPointer = ((UINT_PTR*)((UINT_PTR)target + (TokenToInt64(*aParam[0])-1)*(mSize/(mArraySize ? mArraySize : 1)))); for (int i = param_count_excluding_rvalue - 2;i && *aDeepPointer;i--) aDeepPointer = (UINT_PTR*)*aDeepPointer; aResultToken.value_int64 = (__int64)aDeepPointer; } } aResultToken.symbol = SYM_INTEGER;
tinku99/ahkdll
e4813deef3adc3c5c614c499ff0aca3cc8a2d3ae
.gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ccc72f --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +AutoHotkey.sdf +AutoHotkey.suo +AutoHotkey.vcxproj.user +ComServer_h.h +ComServer_i.c +bin +ipch +temp
tinku99/ahkdll
1adfe3e81ea4e488e34725892b9c02e76199d75f
ComObjDll and ComObjMemDll to load COM object from dll
diff --git a/source/script.cpp b/source/script.cpp index bb09f46..6df62f2 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -9616,1024 +9616,1036 @@ Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool & return FindFunc(aFuncName, aFuncNameLength); } } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Static"))) // lowlevel() Naveen v9. { bif = BIF_Static; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; } else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1. // By design, scripts that use OnMessage are persistent by default. Doing this here // also allows WinMain() to later detect whether this script should become #SingleInstance. // Note: Don't directly change g_AllowOnlyOneInstance here in case the remainder of the // script-loading process comes across any explicit uses of #SingleInstance, which would // override the default set here. g_persistent = true; } #ifdef ENABLE_REGISTERCALLBACK else if (!_tcsicmp(func_name, _T("RegisterCallback"))) { bif = BIF_RegisterCallback; max_params = 4; // Leave min_params at 1. } #endif else if (!_tcsicmp(func_name, _T("IsObject"))) // L31 { bif = BIF_IsObject; max_params = 10000; // Leave min_params at 1. } else if (!_tcsnicmp(func_name, _T("Obj"), 3)) // L31: See script_object.cpp for details. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("ect"))) // i.e. "Object" { bif = BIF_ObjCreate; min_params = 0; max_params = 10000; } #define BIF_OBJ_CASE(aCaseSuffix, aMinParams, aMaxParams) \ else if (!_tcsicmp(suffix, _T(#aCaseSuffix))) \ { \ bif = BIF_Obj##aCaseSuffix; \ min_params = (1 + aMinParams); \ max_params = (1 + aMaxParams); \ } // All of these functions require the "object" parameter, // but it is excluded from the counts below for clarity: BIF_OBJ_CASE(Insert, 1, 10000) // [key,] value [, value2, ...] BIF_OBJ_CASE(Remove, 0, 2) // [min_key, max_key] BIF_OBJ_CASE(MinIndex, 0, 0) BIF_OBJ_CASE(MaxIndex, 0, 0) BIF_OBJ_CASE(HasKey, 1, 1) // key BIF_OBJ_CASE(GetCapacity, 0, 1) // [key] BIF_OBJ_CASE(SetCapacity, 1, 2) // [key,] new_capacity BIF_OBJ_CASE(GetAddress, 1, 1) // key BIF_OBJ_CASE(NewEnum, 0, 0) BIF_OBJ_CASE(Clone, 0, 0) #undef BIF_OBJ_CASE else if (!_tcsicmp(suffix, _T("AddRef")) || !_tcsicmp(suffix, _T("Release"))) bif = BIF_ObjAddRefRelease; else return NULL; } else if (!_tcsicmp(func_name, _T("Array"))) { bif = BIF_ObjArray; min_params = 0; max_params = 10000; } else if (!_tcsicmp(func_name, _T("FileOpen"))) { bif = BIF_FileOpen; min_params = 2; max_params = 3; } else if (!_tcsnicmp(func_name, _T("ComObj"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_ComObjCreate; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get"))) bif = BIF_ComObjGet; + else if (!_tcsicmp(suffix, _T("MemDll"))) + { + bif = BIF_ComObjMemDll; + min_params = 2; + max_params = 2; + } + else if (!_tcsicmp(suffix, _T("Dll"))) + { + bif = BIF_ComObjDll; + min_params = 2; + max_params = 2; + } else if (!_tcsicmp(suffix, _T("Connect"))) { bif = BIF_ComObjConnect; max_params = 2; } else if (!_tcsicmp(suffix, _T("Error"))) { bif = BIF_ComObjError; min_params = 0; } else if (!_tcsicmp(suffix, _T("Type"))) { bif = BIF_ComObjTypeOrValue; max_params = 2; } else if (!_tcsicmp(suffix, _T("Value"))) { bif = BIF_ComObjTypeOrValue; } else if (!_tcsicmp(suffix, _T("Flags"))) { bif = BIF_ComObjFlags; max_params = 3; } else if (!_tcsicmp(suffix, _T("Array"))) { bif = BIF_ComObjArray; min_params = 2; max_params = 9; // up to 8 dimensions } else if (!_tcsicmp(suffix, _T("Query"))) { bif = BIF_ComObjQuery; min_params = 2; max_params = 3; } else { bif = BIF_ComObjActive; min_params = 0; max_params = 3; } } else if (!_tcsicmp(func_name, _T("Exception"))) { bif = BIF_Exception; max_params = 3; } else return NULL; // Maint: There may be other lines above that also return NULL. // Since above didn't return, this is a built-in function that hasn't yet been added to the list. // Add it now: if ( !(pfunc = AddFunc(func_name, aFuncNameLength, true, left)) ) // L27: left contains the position within mFunc to insert the function. Cannot use *apInsertPos as caller may have omitted it or passed NULL. return NULL; pfunc->mBIF = bif; pfunc->mMinParams = min_params; pfunc->mParamCount = max_params; return pfunc; } Func *Script::AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject) // This function should probably not be called by anyone except FindOrAddFunc, which has already done // the dupe-checking. // Returns the address of the new function or NULL on failure. // The caller must already have verified that this isn't a duplicate function. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (aFuncNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Function name too long."), aFuncName); return NULL; } // Make a temporary copy that includes only the first aFuncNameLength characters from aFuncName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // See explanation above. +1 to convert length to size. // In the future, it might be best to add another check here to disallow function names that consist // entirely of numbers. However, this hasn't been done yet because: // 1) Not sure if there will ever be a good enough reason. // 2) Even if it's done in the far future, it won't break many scripts (pure-numeric functions should be very rare). // 3) Those scripts that are broken are not broken in a bad way because the pre-parser will generate a // load-time error, which is easy to fix (unlike runtime errors, which require that part of the script // to actually execute). if (!aClassObject && !Var::ValidateName(func_name, DISPLAY_FUNC_ERROR)) // Variable and function names are both validated the same way. // Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit). return NULL; // Allocate some dynamic memory to pass to the constructor: LPTSTR new_name = SimpleHeap::Malloc(func_name, aFuncNameLength); if (!new_name) // It already displayed the error for us. return NULL; Func *the_new_func = new Func(new_name, aIsBuiltIn); if (!the_new_func) { ScriptError(ERR_OUTOFMEM); return NULL; } if (aClassObject) { LPTSTR key = _tcsrchr(new_name, '.'); if (!key) { ScriptError(_T("Invalid method name."), new_name); // Shouldn't ever happen. return NULL; } if (!aClassObject->SetItem(key + 1, the_new_func)) { ScriptError(ERR_OUTOFMEM); return NULL; } // Also add it to the script's list of functions, to support #Warn LocalSameAsGlobal // and automatic cleanup of objects in static vars on program exit. } if (mFuncCount == mFuncCountMax) { // Allocate or expand function list. int alloc_count = mFuncCountMax ? mFuncCountMax * 2 : 100; Func **temp = (Func **)realloc(mFunc, alloc_count * sizeof(Func *)); // If passed NULL, realloc() will do a malloc(). if (!temp) { ScriptError(ERR_OUTOFMEM); return NULL; } mFunc = temp; mFuncCountMax = alloc_count; } if (aInsertPos != mFuncCount) // Need to make room at the indicated position for this variable. memmove(mFunc + aInsertPos + 1, mFunc + aInsertPos, (mFuncCount - aInsertPos) * sizeof(Func *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. mFunc[aInsertPos] = the_new_func; ++mFuncCount; return the_new_func; } size_t Line::ArgIndexLength(int aArgIndex) // This function is similar to ArgToInt(), so maintain them together. // "ArgLength" is the arg's fully resolved, dereferenced length during runtime. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. // ArgLength() was added in v1.0.44.14 to help its callers improve performance by avoiding // costly calls to _tcslen() (which is especially beneficial for huge strings). { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // Arg doesn't exist, so don't try accessing sArgVar (unlike sArgDeref, it wouldn't be valid to do so). return 0; // i.e. treat it as the empty string. // The length is not known and must be calculated in the following situations: // - The arg consists of more than just a single isolated variable name (not possible if the arg is // ARG_TYPE_INPUT_VAR). // - The arg is a built-in variable, in which case the length isn't known, so it must be derived from // the string copied into sArgDeref[] by an earlier stage. // - The arg is a normal variable but it's VAR_ATTRIB_BINARY_CLIP. In such cases, our callers do not // recognize/support binary-clipboard as binary and want the apparent length of the string returned // (i.e. _tcslen(), which takes into account the position of the first binary zero wherever it may be). if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; // For performance and convenience. if ( var.Type() == VAR_NORMAL // This and below ordered for short-circuit performance based on types of input expected from caller. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) // Although the ones that have the highbit set are hereby omitted from the fast method, the nature of almost all of the highbit commands is such that their performance won't be measurably affected. See ArgMustBeDereferenced() for more info. && (g_NoEnv || var.HasContents()) // v1.0.46.02: Recognize environment variables (when g_NoEnv==FALSE) by falling through to _tcslen() for them. && &var != g_ErrorLevel ) // Mostly for maintainability because the following situation is very rare: If it's g_ErrorLevel, use the deref version instead because if g_ErrorLevel is an input variable in the caller's command, and the caller changes ErrorLevel (such as to set a default) prior to calling this function, the changed/new ErrorLevel will be used rather than its original value (which is usually undesirable). //&& !var.IsBinaryClip()) // This check isn't necessary because the line below handles it. return var.LengthIgnoreBinaryClip(); // Do it the fast way (unless it's binary clipboard, in which case this call will internally call _tcslen()). } // Otherwise, length isn't known due to no variable, a built-in variable, or an environment variable. // So do it the slow way. return _tcslen(sArgDeref[aArgIndex]); } __int64 Line::ArgIndexToInt64(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0; // i.e. treat it as ATOI64(""). // SEE THIS POSITION IN ArgIndexLength() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToInt64(FALSE); } // Otherwise: return ATOI64(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } double Line::ArgIndexToDouble(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0.0; // i.e. treat it as ATOF(""). // SEE THIS POSITION IN ARGLENGTH() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToDouble(FALSE); } // Otherwise: return ATOF(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } Var *Line::ResolveVarOfArg(int aArgIndex, bool aCreateIfNecessary) // Returns NULL on failure. Caller has ensured that none of this arg's derefs are function-calls. // Args that are input or output variables are normally resolved at load-time, so that // they contain a pointer to their Var object. This is done for performance. However, // in order to support dynamically resolved variables names like AutoIt2 (e.g. arrays), // we have to do some extra work here at runtime. // Callers specify false for aCreateIfNecessary whenever the contents of the variable // they're trying to find is unimportant. For example, dynamically built input variables, // such as "StringLen, length, array%i%", do not need to be created if they weren't // previously assigned to (i.e. they weren't previously used as an output variable). // In the above example, the array element would never be created here. But if the output // variable were dynamic, our call would have told us to create it. { // The requested ARG isn't even present, so it can't have a variable. Currently, this should // never happen because the loading procedure ensures that input/output args are not marked // as variables if they are blank (and our caller should check for this and not call in that case): if (aArgIndex >= mArgc) return NULL; ArgStruct &this_arg = mArg[aArgIndex]; // For performance and convenience. // Since this function isn't inline (since it's called so frequently), there isn't that much more // overhead to doing this check, even though it shouldn't be needed since it's the caller's // responsibility: if (this_arg.type == ARG_TYPE_NORMAL) // Arg isn't an input or output variable. return NULL; if (!*this_arg.text) // The arg's variable is not one that needs to be dynamically resolved. return VAR(this_arg); // Return the var's address that was already determined at load-time. // The above might return NULL in the case where the arg is optional (i.e. the command allows // the var name to be omitted). But in that case, the caller should either never have called this // function or should check for NULL upon return. UPDATE: This actually never happens, see // comment above the "if (aArgIndex >= mArgc)" line. // Static to correspond to the static empty_var further below. It needs the memory area // to support resolving dynamic environment variables. In the following example, // the result will be blank unless the first line is present (without this fix here): //null = %SystemRoot% ; bogus line as a required workaround in versions prior to v1.0.16 //thing = SystemRoot //StringTrimLeft, output, %thing%, 0 //msgbox %output% static TCHAR sVarName[MAX_VAR_NAME_LENGTH + 1]; // Will hold the dynamically built name. // At this point, we know the requested arg is a variable that must be dynamically resolved. // This section is similar to that in ExpandArg(), so they should be maintained together: LPTSTR pText = this_arg.text; // Start at the beginning of this arg's text. size_t var_name_length = 0; if (this_arg.deref) // There's at least one deref. { // Caller has ensured that none of these derefs are function calls (i.e. deref->is_function is alway false). for (DerefType *deref = this_arg.deref // Start off by looking for the first deref. ; deref->marker; ++deref) // A deref with a NULL marker terminates the list. { // FOR EACH DEREF IN AN ARG (if we're here, there's at least one): // Copy the chars that occur prior to deref->marker into the buffer: for (; pText < deref->marker && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && pText < deref->marker) // The variable name would be too long! { // This type of error is just a warning because this function isn't set up to cause a true // failure. This is because the use of dynamically named variables is rare, and only for // people who should know what they're doing. In any case, when the caller of this // function called it to resolve an output variable, it will see the the result is // NULL and terminate the current subroutine. #define DYNAMIC_TOO_LONG _T("This dynamically built variable name is too long.") \ _T(" If this variable was not intended to be dynamic, remove the % symbols from it.") LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } // Now copy the contents of the dereferenced var. For all cases, aBuf has already // been verified to be large enough, assuming the value hasn't changed between the // time we were called and the time the caller calculated the space needed. if (deref->var->Get() > (VarSizeType)(MAX_VAR_NAME_LENGTH - var_name_length)) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } var_name_length += deref->var->Get(sVarName + var_name_length); // Finally, jump over the dereference text. Note that in the case of an expression, there might not // be any percent signs within the text of the dereference, e.g. x + y, not %x% + %y%. pText += deref->length; } } // Copy any chars that occur after the final deref into the buffer: for (; *pText && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && *pText) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } if (!var_name_length) { LineError(_T("This dynamic variable is blank. If this variable was not intended to be dynamic,") _T(" remove the % symbols from it."), FAIL, this_arg.text); return NULL; } // Terminate the buffer, even if nothing was written into it: sVarName[var_name_length] = '\0'; static Var empty_var(sVarName, (void *)VAR_NORMAL, false); // Must use sVarName here. See comment above for why. Var *found_var; if (!aCreateIfNecessary) { // Now we've dynamically build the variable name. It's possible that the name is illegal, // so check that (the name is automatically checked by FindOrAddVar(), so we only need to // check it if we're not calling that): if (!Var::ValidateName(sVarName)) return NULL; // Above already displayed error for us. if (found_var = g_script.FindVar(sVarName, var_name_length)) // Assign. return found_var; // At this point, this is either a non-existent variable or a reserved/built-in variable // that was never statically referenced in the script (only dynamically), e.g. A_IPAddress%A_Index% if (Script::GetVarType(sVarName) == (void *)VAR_NORMAL) // If not found: for performance reasons, don't create it because caller just wants an empty variable. return &empty_var; //else it's the clipboard or some other built-in variable, so continue onward so that the // variable gets created in the variable list, which is necessary to allow it to be properly // dereferenced, e.g. in a script consisting of only the following: // Loop, 4 // StringTrimRight, IP, A_IPAddress%A_Index%, 0 } // Otherwise, aCreateIfNecessary is true or we want to create this variable unconditionally for the // reason described above. if ( !(found_var = g_script.FindOrAddVar(sVarName, var_name_length)) ) return NULL; // Above will already have displayed the error. if (this_arg.type == ARG_TYPE_OUTPUT_VAR && VAR_IS_READONLY(*found_var)) { LineError(ERR_VAR_IS_READONLY, FAIL, sVarName); return NULL; // Don't return the var, preventing the caller from assigning to it. } else return found_var; } Var *Script::FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength, int aScope) // Caller has ensured that aVarName isn't NULL. // Returns the Var whose name matches aVarName. If it doesn't exist, it is created. { if (!*aVarName) return NULL; int insert_pos; bool is_local; // Used to detect which type of var should be added in case the result of the below is NULL. Var *var; if (var = FindVar(aVarName, aVarNameLength, &insert_pos, aScope, &is_local)) return var; // Otherwise, no match found, so create a new var. This will return NULL if there was a problem, // in which case AddVar() will already have displayed the error: return AddVar(aVarName, aVarNameLength, insert_pos , (aScope & ~(VAR_LOCAL | VAR_GLOBAL)) | (is_local ? VAR_LOCAL : VAR_GLOBAL)); // When aScope == FINDVAR_DEFAULT, it contains both the "local" and "global" bits. This ensures only the appropriate bit is set. } Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, int aScope , bool *apIsLocal) // Caller has ensured that aVarName isn't NULL. It must also ignore the contents of apInsertPos when // a match (non-NULL value) is returned. // Returns the Var whose name matches aVarName. If it doesn't exist, NULL is returned. // If caller provided a non-NULL apInsertPos, it will be given a the array index that a newly // inserted item should have to keep the list in sorted order (which also allows the ListVars command // to display the variables in alphabetical order). { if (!*aVarName) return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. When the caller later // tries to add the variable, it will get an error then: if (aVarNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the various searches below to use _tcsicmp() instead of // strlicmp(), which close to doubles their performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR var_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(var_name, aVarName, aVarNameLength + 1); // +1 to convert length to size. global_struct &g = *::g; // Reduces code size and may improve performance. bool search_local = (aScope & VAR_LOCAL) && g.CurrentFunc; // Above has ensured that g.CurrentFunc!=NULL whenever search_local==true. // Init for binary search loop: int left, right, mid, result; // left/right must be ints to allow them to go negative and detect underflow. Var **var; // An array of pointers-to-var. if (search_local) { var = g.CurrentFunc->mVar; right = g.CurrentFunc->mVarCount - 1; } else { var = mVar; right = mVarCount - 1; } // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } // Since above didn't return, no match was found in the main list, so search the lazy list if there // is one. If there's no lazy list, the value of "left" established above will be used as the // insertion point further below: if (search_local) { var = g.CurrentFunc->mLazyVar; right = g.CurrentFunc->mLazyVarCount - 1; } else { var = mLazyVar; right = mLazyVarCount - 1; } if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below). { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } // Since above didn't return, no match was found and "left" always contains the position where aVarName // should be inserted to keep the list sorted. The item is always inserted into the lazy list unless // there is no lazy list. // Set the output parameter, if present: if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below. *apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order. if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match. *apIsLocal = search_local; // Since no match was found, if this is a local fall back to searching the list of globals at runtime diff --git a/source/script.h b/source/script.h index 1ada3b7..43725db 100644 --- a/source/script.h +++ b/source/script.h @@ -2055,1022 +2055,1025 @@ public: Line *line; for (line = mJumpToLine; line && (line->mActionType != ACT_BLOCK_END || !line->mAttribute); line = line->mNextLine); // Give user the opportunity to inspect variables before returning. if (line) g_Debugger.PreExecLine(line); } } #endif DEBUGGER_STACK_POP() --mInstances; // Restore the original value in case this function is called from inside another function. // Due to the synchronous nature of recursion and recursion-collapse, this should keep // g->CurrentFunc accurate, even amidst the asynchronous saving and restoring of "g" itself: g->CurrentFunc = prev_func; return result; } // IObject. ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); ULONG STDMETHODCALLTYPE AddRef() { return 1; } ULONG STDMETHODCALLTYPE Release() { return 1; } Func(LPTSTR aFuncName, bool aIsBuiltIn) // Constructor. : mName(aFuncName) // Caller gave us a pointer to dynamic memory for this. , mBIF(NULL) , mParam(NULL), mParamCount(0), mMinParams(0) , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mGlobalVar(NULL), mGlobalVarCount(0) , mInstances(0) , mDefaultVarType(VAR_DECLARE_NONE) , mIsBuiltIn(aIsBuiltIn) , mIsVariadic(false) {} 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) {} void operator delete[](void *aPtr) {} }; class ExprOpFunc : public Func { // 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 to pass a simple // identifier to mBIF (currently only BIF_ObjInvoke). public: ExprOpFunc(BuiltInFunctionType aBIF, INT_PTR aID, int aMinParams = 1, int aParamCount = 1000) : Func((LPTSTR)aID, true) { mBIF = aBIF; mMinParams = aMinParams; // These are only enforced in some cases. mParamCount = aParamCount; // } }; class ScriptTimer { public: Label *mLabel; 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. bool mEnabled; bool mRunOnlyOnce; ScriptTimer *mNextTimer; // Next items in linked list void ScriptTimer::Disable(); ScriptTimer(Label *aLabel) #define DEFAULT_TIMER_PERIOD 250 : mLabel(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. {} 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) {} void operator delete[](void *aPtr) {} }; struct MsgMonitorStruct { Func *func; UINT msg; // Keep any members smaller than 4 bytes adjacent to save memory: short instance_count; // Distinct from func.mInstances because the script might have called the function explicitly. short max_instances; // v1.0.47: Support more than one thread. }; #ifndef MINIDLL #define MAX_MENU_NAME_LENGTH MAX_PATH // For both menu and menu item names. class UserMenuItem; // Forward declaration since classes use each other (i.e. a menu *item* can have a submenu). class UserMenu { public: LPTSTR mName; // Dynamically allocated. UserMenuItem *mFirstMenuItem, *mLastMenuItem, *mDefault; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: bool mIncludeStandardItems; int mClickCount; // How many clicks it takes to trigger the default menu item. 2 = double-click UINT mMenuItemCount; // The count of user-defined menu items (doesn't include the standard items, if present). UserMenu *mNextMenu; // Next item in linked list HMENU mMenu; MenuTypeType mMenuType; // MENU_TYPE_POPUP (via CreatePopupMenu) vs. MENU_TYPE_BAR (via CreateMenu). HBRUSH mBrush; // Background color to apply to menu. COLORREF mColor; // The color that corresponds to the above. // 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(LPTSTR aName) // Constructor : mName(aName), mFirstMenuItem(NULL), mLastMenuItem(NULL), mDefault(NULL) , mIncludeStandardItems(false), mClickCount(2), mMenuItemCount(0), mNextMenu(NULL), mMenu(NULL) , mMenuType(MENU_TYPE_POPUP) // The MENU_TYPE_NONE flag is not used in this context. Default = POPUP. , mBrush(NULL), mColor(CLR_DEFAULT) { } ResultType AddItem(LPTSTR aName, UINT aMenuID, Label *aLabel, UserMenu *aSubmenu, LPTSTR aOptions); ResultType DeleteItem(UserMenuItem *aMenuItem, UserMenuItem *aMenuItemPrev); ResultType DeleteAllItems(); ResultType ModifyItem(UserMenuItem *aMenuItem, Label *aLabel, UserMenu *aSubmenu, LPTSTR aOptions); void UpdateOptions(UserMenuItem *aMenuItem, LPTSTR aOptions); ResultType RenameItem(UserMenuItem *aMenuItem, LPTSTR aNewName); ResultType UpdateName(UserMenuItem *aMenuItem, LPTSTR aNewName); ResultType CheckItem(UserMenuItem *aMenuItem); ResultType UncheckItem(UserMenuItem *aMenuItem); ResultType ToggleCheckItem(UserMenuItem *aMenuItem); ResultType EnableItem(UserMenuItem *aMenuItem); ResultType DisableItem(UserMenuItem *aMenuItem); ResultType ToggleEnableItem(UserMenuItem *aMenuItem); ResultType SetDefault(UserMenuItem *aMenuItem = NULL); ResultType IncludeStandardItems(); ResultType ExcludeStandardItems(); ResultType Create(MenuTypeType aMenuType = MENU_TYPE_NONE); // NONE means UNSPECIFIED in this context. void SetColor(LPTSTR aColorName, bool aApplyToSubmenus); void ApplyColor(bool aApplyToSubmenus); ResultType AppendStandardItems(); ResultType Destroy(); ResultType Display(bool aForceToForeground = true, int aX = COORD_UNSPECIFIED, int aY = COORD_UNSPECIFIED); UINT GetSubmenuPos(HMENU ahMenu); UINT GetItemPos(LPTSTR aMenuItemName); bool ContainsMenu(UserMenu *aMenu); void UpdateAccelerators(); // L17: Functions for menu icons. ResultType SetItemIcon(UserMenuItem *aMenuItem, LPTSTR aFilename, int aIconNumber, int aWidth); ResultType ApplyItemIcon(UserMenuItem *aMenuItem); ResultType RemoveItemIcon(UserMenuItem *aMenuItem); static BOOL OwnerMeasureItem(LPMEASUREITEMSTRUCT aParam); static BOOL OwnerDrawItem(LPDRAWITEMSTRUCT aParam); }; class UserMenuItem { public: LPTSTR mName; // Dynamically allocated. size_t mNameCapacity; UINT mMenuID; Label *mLabel; UserMenu *mSubmenu; UserMenu *mMenu; // The menu to which this item belongs. Needed to support script var A_ThisMenu. int mPriority; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: bool mEnabled, mChecked; UserMenuItem *mNextMenuItem; // Next item in linked list union { // L17: Implementation of menu item icons is OS-dependent (g_os.IsWinVistaOrLater()). // Older versions of Windows do not support alpha channels in menu item bitmaps, so owner-drawing // must be used for icons with transparent backgrounds to appear correctly. Owner-drawing also // prevents the icon colours from inverting when the item is selected. DrawIcon() gives the best // results, so we store the icon handle as is. // HICON mIcon; // 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; }; // Constructor: UserMenuItem(LPTSTR aName, size_t aNameCapacity, UINT aMenuID, Label *aLabel, UserMenu *aSubmenu, UserMenu *aMenu); // 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). }; struct FontType { #define MAX_FONT_NAME_LENGTH 63 // Longest name I've seen is 29 chars, "Franklin Gothic Medium Italic". Anyway, there's protection against overflow. TCHAR name[MAX_FONT_NAME_LENGTH + 1]; // Keep any fields that aren't an even multiple of 4 adjacent to each other. This conserves memory // due to byte-alignment: bool italic; bool underline; bool strikeout; int point_size; // Decided to use int vs. float to simplify the code in many places. Fractional sizes seem rarely needed. int weight; DWORD quality; // L19: Allow control over font quality (anti-aliasing, etc.). HFONT hfont; }; #endif #define LV_REMOTE_BUF_SIZE 1024 // 8192 (below) seems too large in hindsight, given that an LV can only display the first 260 chars in a field. #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. #ifndef MINIDLL 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 { HWND hwnd; // 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; #define GUI_CONTROL_ATTRIB_IMPLICIT_CANCEL 0x01 #define GUI_CONTROL_ATTRIB_ALTSUBMIT 0x02 #define GUI_CONTROL_ATTRIB_LABEL_IS_RUNNING 0x04 #define GUI_CONTROL_ATTRIB_EXPLICITLY_HIDDEN 0x08 #define GUI_CONTROL_ATTRIB_EXPLICITLY_DISABLED 0x10 #define GUI_CONTROL_ATTRIB_BACKGROUND_DEFAULT 0x20 // i.e. Don't conform to window/control background color; use default instead. #define GUI_CONTROL_ATTRIB_BACKGROUND_TRANS 0x40 // i.e. Leave this control's background transparent. #define GUI_CONTROL_ATTRIB_ALTBEHAVIOR 0x80 // For sliders: Reverse/Invert the value. Also for up-down controls (ALT means 32-bit vs. 16-bit). Also for ListView and Tab, and for Edit. UCHAR attrib; // A field of option flags/bits defined above. TabControlIndexType tab_control_index; // Which tab control this control belongs to, if any. TabIndexType tab_index; // For type==TAB, this stores the tab control's index. For other types, it stores the page. Var *output_var; Label *jump_to_label; union { COLORREF union_color; // Color of the control's text. HBITMAP union_hbitmap; // 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. }; #define USES_FONT_AND_TEXT_COLOR(type) !(type == GUI_CONTROL_PIC || type == GUI_CONTROL_UPDOWN \ || type == GUI_CONTROL_SLIDER || type == GUI_CONTROL_PROGRESS) }; struct GuiControlOptionsType { DWORD style_add, style_remove, exstyle_add, exstyle_remove, listview_style; int listview_view; // Viewing mode, such as LVS_ICON, LVS_REPORT. Int vs. DWORD to more easily use any negative value as "invalid". HIMAGELIST himagelist; Var *hwnd_output_var; // v1.0.46.01: Allows a script to retrieve the control's HWND upon creation of control. 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_listview; // Used only for those controls that need control.union_color for something other than 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 color_changed; // To discern when a control has been put back to the default color. [v1.0.26] 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. }; LRESULT CALLBACK GuiWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK TabWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); class GuiType { public: #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 * sFont[mCurrentFontIndex].point_size) // 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 8 #define PROGRESS_DEFAULT_THICKNESS (2 * sFont[mCurrentFontIndex].point_size) LPTSTR mName; HWND mHwnd, 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 the below amount. This offset is // necessary because windows that behave like dialogs automatically return IDOK and IDCANCEL in // response to certain types of standard actions: GuiIndexType mControlCount; GuiIndexType mControlCapacity; // How many controls can fit into the current memory size of mControl. GuiControlType *mControl; // Will become an array of controls when the window is first created. GuiIndexType mDefaultButtonIndex; // Index vs. pointer is needed for some things. ULONG mReferenceCount; // For keeping this structure in memory during execution of the Gui's labels. Label *mLabelForClose, *mLabelForEscape, *mLabelForSize, *mLabelForDropFiles, *mLabelForContextMenu; bool mLabelForCloseIsRunning, mLabelForEscapeIsRunning, mLabelForSizeIsRunning; // DropFiles doesn't need one of these. bool mLabelsHaveBeenSet; DWORD mStyle, mExStyle; // Style of window. 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. TCHAR mDelimiter; // The default field delimiter when adding items to ListBox, DropDownList, ListView, etc. GuiControlType *mCurrentListView, *mCurrentTreeView; // The ListView and TreeView upon which the LV/TV functions operate. int mCurrentFontIndex; COLORREF mCurrentColor; // The default color of text in controls. COLORREF mBackgroundColorWin; // The window's background color itself. COLORREF mBackgroundColorCtl; // Background color for controls. HBRUSH mBackgroundBrushWin; // Brush corresponding to mBackgroundColorWin. HBRUSH mBackgroundBrushCtl; // Brush corresponding to mBackgroundColorCtl. 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. int mMarginX, mMarginY, mPrevX, mPrevY, mPrevWidth, mPrevHeight, mMaxExtentRight, mMaxExtentDown , mSectionX, mSectionY, mMaxExtentRightSection, mMaxExtentDownSection; LONG mMinWidth, mMinHeight, mMaxWidth, mMaxHeight; 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 mGuiShowHasNeverBeenDone, mFirstActivation, mShowIsInProgress, mDestroyWindowHasBeenCalled; bool mControlWidthWasSetByContents; // Whether the most recently added control was auto-width'd to fit its contents. #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). // Keep the default destructor to avoid entering the "Law of the Big Three": If your class requires a // copy constructor, copy assignment operator, or a destructor, then it very likely will require all three. GuiType() // Constructor : mName(NULL), mHwnd(NULL), mStatusBarHwnd(NULL), mControlCount(0), mControlCapacity(0) , mDefaultButtonIndex(-1), mLabelForClose(NULL), mLabelForEscape(NULL), mLabelForSize(NULL) , mLabelForDropFiles(NULL), mLabelForContextMenu(NULL), mReferenceCount(1) , mLabelForCloseIsRunning(false), mLabelForEscapeIsRunning(false), mLabelForSizeIsRunning(false) , mLabelsHaveBeenSet(false) // 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), mOwner(NULL), mDelimiter('|') , mCurrentFontIndex(FindOrCreateFont()) // Must call this in constructor to ensure sFont array is never NULL while a GUI object exists. Omit params to tell it to find or create DEFAULT_GUI_FONT. , mCurrentListView(NULL), mCurrentTreeView(NULL) , mTabControlCount(0), mCurrentTabControlIndex(MAX_TAB_CONTROLS), mCurrentTabIndex(0) , mCurrentColor(CLR_DEFAULT) , mBackgroundColorWin(CLR_DEFAULT), mBackgroundBrushWin(NULL) , mBackgroundColorCtl(CLR_DEFAULT), mBackgroundBrushCtl(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) { // The array of controls is left uninitialized to catch bugs. Each control's attributes should be // fully populated when it is created. //ZeroMemory(mControl, sizeof(mControl)); } static ResultType Destroy(GuiType &gui); static void DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall); // L17: Renamed function and added parameter to also handle the window's small icon. ResultType Create(); void AddRef(); void Release(); void SetLabels(LPTSTR aLabelPrefix); static void UpdateMenuBars(HMENU aMenu); ResultType AddControl(GuiControls aControlType, LPTSTR aOptions, LPTSTR aText); ResultType ParseOptions(LPTSTR aOptions, bool &aSetLastFoundWindow, ToggleValueType &aOwnDialogs, Var *&aHwndVar); void GetNonClientArea(LONG &aWidth, LONG &aHeight); void GetTotalWidthAndHeight(LONG &aWidth, LONG &aHeight); ResultType ControlParseOptions(LPTSTR aOptions, GuiControlOptionsType &aOpt, GuiControlType &aControl , GuiIndexType aControlIndex = -1); // aControlIndex is not needed upon control creation. void ControlInitOptions(GuiControlOptionsType &aOpt, GuiControlType &aControl); void ControlAddContents(GuiControlType &aControl, LPTSTR aContent, int aChoice, GuiControlOptionsType *aOpt = NULL); ResultType Show(LPTSTR aOptions, LPTSTR aTitle); ResultType Clear(); ResultType Cancel(); ResultType Close(); // Due to SC_CLOSE, etc. ResultType Escape(); // Similar to close, except typically called when the user presses ESCAPE. ResultType Submit(bool aHideIt); ResultType ControlGetContents(Var &aOutputVar, GuiControlType &aControl, LPTSTR aMode = _T("")); static VarSizeType ControlGetName(GuiType *aGuiWindow, GuiIndexType aControlIndex, LPTSTR aBuf); static GuiType *FindGui(LPTSTR aName); static GuiType *FindGui(HWND aHwnd); static GuiType *ValidGui(GuiType *&aGuiRef); // Updates aGuiRef if it points to a destroyed Gui. GuiIndexType FindControl(LPTSTR aControlID); GuiControlType *FindControl(HWND aHwnd, bool aRetrieveIndexInstead = false) { 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) // Not found yet; try again with parent. { // Since ComboBoxes (and possibly other future control types) have children, try looking // up aHwnd's parent to see if its a known control of this dialog. Some callers rely on us making // this extra effort: if (aHwnd = GetParent(aHwnd)) // 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. 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) // A match was found. return aRetrieveIndexInstead ? (GuiControlType *)(size_t)index : mControl + index; else // No match, so indicate failure. return aRetrieveIndexInstead ? (GuiControlType *)NO_CONTROL_INDEX : NULL; } int FindGroup(GuiIndexType aControlIndex, GuiIndexType &aGroupStart, GuiIndexType &aGroupEnd); ResultType SetCurrentFont(LPTSTR aOptions, LPTSTR aFontName); static int FindOrCreateFont(LPTSTR aOptions = _T(""), LPTSTR aFontName = _T(""), FontType *aFoundationFont = NULL , COLORREF *aColor = NULL); static int FindFont(FontType &aFont); void Event(GuiIndexType aControlIndex, UINT aNotifyCode, USHORT aGuiEvent = GUI_EVENT_NONE, UINT aEventInfo = 0); static WORD TextToHotkey(LPTSTR aText); static LPTSTR HotkeyToText(WORD aHotkey, LPTSTR aBuf); 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); bool ControlOverrideBkColor(GuiControlType &aControl); 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); POINT GetPositionOfTabClientArea(GuiControlType &aTabControl); ResultType SelectAdjacentTab(GuiControlType &aTabControl, bool aMoveToRight, bool aFocusFirstControl , bool aWrapAround); void ControlGetPosOfFocusedItem(GuiControlType &aControl, POINT &aPoint); static void LV_Sort(GuiControlType &aControl, int aColumnIndex, bool aSortOnlyIfEnabled, TCHAR aForceDirection = '\0'); static DWORD ControlGetListViewMode(HWND aWnd); 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); }; #endif // MINIDLL typedef NTSTATUS (NTAPI *PFN_NT_QUERY_INFORMATION_PROCESS) ( HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength OPTIONAL); + typedef int (* ahkx_int_str)(LPTSTR ahkx_str); // ahkx N11 typedef int (* ahkx_int_str_str)(LPTSTR ahkx_str, LPTSTR ahkx_str2); // ahkx N11 class Script { private: #ifndef MINIDLL friend class Hotkey; #endif #ifdef CONFIG_DEBUGGER friend class Debugger; #endif public: Var **mVar, **mLazyVar; // Array of pointers-to-variable, allocated upon first use and later expanded as needed. int mVarCount, mVarCountMax, mLazyVarCount; // Count of items in the above array as well as the maximum capacity. WinGroup *mFirstGroup, *mLastGroup; // The first and last variables in the linked list. int mCurrentFuncOpenBlockCount; // While loading the script, this is how many blocks are currently open in the current function's body. bool mNextLineIsFunctionBody; // Whether the very next line to be added will be the first one of the body. #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. // 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 mNoHotkeyLabels; #ifndef MINIDLL bool mMenuUseErrorLevel; // Whether runtime errors should be displayed by the Menu command, vs. ErrorLevel. #endif #define UPDATE_TIP_FIELD tcslcpy(mNIC.szTip, (mTrayIconTip && *mTrayIconTip) ? mTrayIconTip \ : (mFileName ? mFileName : T_AHK_NAME), _countof(mNIC.szTip)); NOTIFYICONDATA mNIC; // For ease of adding and deleting our tray icon. size_t GetLine(LPTSTR aBuf, int aMaxCharsToRead, int aInContinuationSection, TextStream *ts); ResultType IsDirective(LPTSTR aBuf); ResultType ParseAndAddLine(LPTSTR aLineText, ActionTypeType aActionType = ACT_INVALID , ActionTypeType aOldActionType = OLD_INVALID, LPTSTR aActionName = NULL , LPTSTR aEndMarker = NULL, LPTSTR aLiteralMap = NULL, size_t aLiteralMapLength = 0); ResultType ParseDerefs(LPTSTR aArgText, LPTSTR aArgMap, DerefType *aDeref, int &aDerefCount); LPTSTR ParseActionType(LPTSTR aBufTarget, LPTSTR aBufSource, bool aDisplayErrors); static ActionTypeType ConvertActionType(LPTSTR aActionTypeString); static ActionTypeType ConvertOldActionType(LPTSTR aActionTypeString); ResultType AddLabel(LPTSTR aLabelName, bool aAllowDupe); ResultType AddLine(ActionTypeType aActionType, LPTSTR aArg[] = NULL, int aArgc = 0, LPTSTR aArgMap[] = NULL); // These aren't in the Line class because I think they're easier to implement // if aStartingLine is allowed to be NULL (for recursive calls). If they // were member functions of class Line, a check for NULL would have to // be done before dereferencing any line's mNextLine, for example: Line *PreparseBlocks(Line *aStartingLine, bool aFindBlockEnd = false, Line *aParentLine = NULL); Line *PreparseIfElse(Line *aStartingLine, ExecUntilMode aMode = NORMAL_MODE, AttributeType aLoopType = ATTR_NONE); Line *mFirstLine, *mLastLine; // The first and last lines in the linked list. Line *mFirstStaticLine, *mLastStaticLine; // The first and last static var initializer. Label *mFirstLabel, *mLastLabel; // The first and last labels in the linked list. Func **mFunc; // Binary-searchable array of functions. int mFuncCount, mFuncCountMax; Line *mTempLine; // for use with dll Execute # Naveen N9 Label *mTempLabel; // for use with dll Execute # Naveen N9 Func *mTempFunc; // for use with dll Execute # Naveen N9 ahkx_int_str xifwinactive ; // ahkx N11 context sensitivity ahkx_int_str xwingetid ; // ahkx_int_str_str xsend ; // ahksend // Naveen moved above from private Line *mCurrLine; // Seems better to make this public than make Line our friend. Label *mPlaceholderLabel; // Used in place of a NULL label to simplify code. #ifndef MINIDLL TCHAR mThisMenuItemName[MAX_MENU_NAME_LENGTH + 1]; TCHAR mThisMenuName[MAX_MENU_NAME_LENGTH + 1]; LPTSTR mThisHotkeyName, mPriorHotkeyName; #endif HWND mNextClipboardViewer; bool mOnClipboardChangeIsRunning; Label *mOnClipboardChangeLabel, *mOnExitLabel; // The label to run when the script terminates (NULL if none). ExitReasons mExitReason; ScriptTimer *mFirstTimer, *mLastTimer; // The first and last script timers in the linked list. UINT mTimerCount, mTimerEnabledCount; #ifndef MINIDLL UserMenu *mFirstMenu, *mLastMenu; UINT mMenuCount; #endif DWORD mThisHotkeyStartTime, mPriorHotkeyStartTime; // Tickcount timestamp of when its subroutine began. #ifndef MINIDLL TCHAR mEndChar; // The ending character pressed to trigger the most recent non-auto-replace hotstring. #endif 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 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. bool mIsReadyToExecute; bool mAutoExecSectionIsRunning; bool mIsRestart; // The app is restarting rather than starting from scratch. bool mIsAutoIt2; // Whether this script is considered to be an AutoIt2 script. bool mErrorStdOut; // true if load-time syntax errors should be sent to stdout vs. a MsgBox. #ifdef AUTOHOTKEYSC bool mCompiledHasCustomIcon; // Whether the compiled script uses a custom icon. #else TextStream *mIncludeLibraryFunctionsThenExit; #endif __int64 mLinesExecutedThisCycle; // Use 64-bit to match the type of g->LinesPerCycle int mUninterruptedLineCountMax; // 32-bit for performance (since huge values seem unnecessary here). int mUninterruptibleTime; DWORD mLastScriptRest, mLastPeekTime; CStringW mRunAsUser, mRunAsPass, mRunAsDomain; #ifndef MINIDLL 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. #endif #ifdef _USRDLL void Destroy(); // HotKeyIt H1 destroy script #endif ResultType Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance,bool aIsText); // ResultType InitDll(global_struct &g,HINSTANCE hInstance); // HotKeyIt init dll from text ResultType CreateWindows(); #ifndef MINIDLL void EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags); void CreateTrayIcon(); void UpdateTrayIcon(bool aForceUpdate = false); #endif ResultType AutoExecSection(); #ifndef MINIDLL ResultType Edit(); #endif ResultType Reload(bool aDisplayErrors); ResultType ExitApp(ExitReasons aExitReason, LPTSTR aBuf = NULL, int ExitCode = 0); void TerminateApp(ExitReasons aExitReason, int aExitCode); // L31: Added aExitReason. See script.cpp. #ifdef AUTOHOTKEYSC LineNumberType LoadFromFile(); #else LineNumberType LoadFromFile(bool aScriptWasNotspecified); #endif #ifndef AUTOHOTKEYSC LineNumberType LoadFromText(LPTSTR aScript); // HotKeyIt H1 load text instead file ahktextdll ResultType LoadIncludedText(LPTSTR aFileSpec); //New read text #endif ResultType LoadIncludedFile(LPTSTR aFileSpec, bool aAllowDuplicateInclude, bool aIgnoreLoadFailure); ResultType UpdateOrCreateTimer(Label *aLabel, LPTSTR aPeriod, LPTSTR aPriority, bool aEnable , bool aUpdatePriorityOnly); ResultType DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]); #ifndef AUTOHOTKEYSC Func *FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude); #endif Func *FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength = 0, int *apInsertPos = NULL); Func *AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject = NULL); ResultType DefineClass(LPTSTR aBuf); ResultType DefineClassVars(LPTSTR aBuf, bool aStatic); Object *FindClass(LPCTSTR aClassName, size_t aClassNameLength = 0); int AddBIF(LPTSTR aFuncName, BuiltInFunctionType bif, size_t minparams, size_t maxparams); // N10 added for dynamic BIFs #define FINDVAR_DEFAULT (VAR_LOCAL | VAR_GLOBAL) #define FINDVAR_GLOBAL VAR_GLOBAL #define FINDVAR_LOCAL VAR_LOCAL Var *FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength = 0, int aScope = FINDVAR_DEFAULT); Var *FindVar(LPTSTR aVarName, size_t aVarNameLength = 0, int *apInsertPos = NULL , int aScope = FINDVAR_DEFAULT , bool *apIsLocal = NULL); Var *AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope); static void *GetVarType(LPTSTR aVarName); WinGroup *FindGroup(LPTSTR aGroupName, bool aCreateIfNotFound = false); ResultType AddGroup(LPTSTR aGroupName); Label *FindLabel(LPTSTR aLabelName); ResultType DoRunAs(LPTSTR aCommandLine, LPTSTR aWorkingDir, bool aDisplayErrors, bool aUpdateLastError, WORD aShowWindow , Var *aOutputVar, PROCESS_INFORMATION &aPI, bool &aSuccess, HANDLE &aNewProcess, LPTSTR aSystemErrorText); ResultType ActionExec(LPTSTR aAction, LPTSTR aParams = NULL, LPTSTR aWorkingDir = NULL , bool aDisplayErrors = true, LPTSTR aRunShowMode = NULL, HANDLE *aProcess = NULL , bool aUpdateLastError = false, bool aUseRunAs = false, Var *aOutputVar = NULL); #ifndef MINIDLL LPTSTR ListVars(LPTSTR aBuf, int aBufSize); LPTSTR ListKeyHistory(LPTSTR aBuf, int aBufSize); ResultType PerformMenu(LPTSTR aMenu, LPTSTR aCommand, LPTSTR aParam3, LPTSTR aParam4, LPTSTR aOptions, LPTSTR aOptions2); // L17: Added aOptions2 for Icon sub-command (icon width). Arg was previously reserved/unused. UserMenu *FindMenu(LPTSTR aMenuName); UserMenu *AddMenu(LPTSTR aMenuName); ResultType ScriptDeleteMenu(UserMenu *aMenu); UserMenuItem *FindMenuItemByID(UINT aID) { UserMenuItem *mi; for (UserMenu *m = mFirstMenu; m; m = m->mNextMenu) for (mi = m->mFirstMenuItem; mi; mi = mi->mNextMenuItem) if (mi->mMenuID == 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; } ResultType PerformGui(LPTSTR aBuf, LPTSTR aControlType, LPTSTR aOptions, LPTSTR aParam4); static GuiType *ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName = NULL, size_t *aNameLength = NULL); #endif // Call this SciptError to avoid confusion with Line's error-displaying functions: ResultType ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo = _T("")); // , ResultType aErrorType = FAIL); void ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo = _T(""), Line *line = NULL); void WarnUninitializedVar(Var *var); void MaybeWarnLocalSameAsGlobal(Func &func, Var &var); void PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount); static ResultType UnhandledException(ExprTokenType*& aToken, Line* aLine); static ResultType SetErrorLevelOrThrow() { return SetErrorLevelOrThrowBool(true); } static ResultType SetErrorLevelOrThrowBool(bool aError); static ResultType SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue); static ResultType SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat); static ResultType ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat = NULL, LPCTSTR aExtraInfo = _T("")); static void FreeExceptionToken(ExprTokenType*& 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 // //////////////////////// VarSizeType BIV_True_False(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MMM_DDD(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DateTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_BatchLines(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchMode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TitleMatchModeSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenWindows(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DetectHiddenText(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AutoTrim(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_StringCaseSense(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatInteger(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FormatFloat(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_KeyDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ControlDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_MouseDelay(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DefaultMouseSpeed(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsPaused(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsCritical(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IsSuspended(LPTSTR aBuf, LPTSTR aVarName); #endif //#ifdef AUTOHOTKEYSC // A_IsCompiled is left blank/undefined in uncompiled scripts. VarSizeType BIV_IsCompiled(LPTSTR aBuf, LPTSTR aVarName); //#endif VarSizeType BIV_IsUnicode(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_FileEncoding(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LastError(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_IconHidden(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconTip(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IconNumber(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_ExitReason(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Space_Tab(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_AhkPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_DllPath(LPTSTR aBuf, LPTSTR aVarName); // HotKeyIt H1 path of loaded dll VarSizeType BIV_TickCount(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Now(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_OSVersion(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Language(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_UserName_ComputerName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WorkingDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_WinDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Temp(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ComSpec(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_SpecialFolderPath(LPTSTR aBuf, LPTSTR aVarName); // Handles various variables. VarSizeType BIV_MyDocuments(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Caret(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Cursor(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScreenWidth_Height(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ScriptHwnd(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineNumber(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LineFile(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileExt(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName); #ifndef MINIDLL VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PriorKey(LPTSTR aBuf, LPTSTR aVarName); #endif VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IPAddress(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_IsAdmin(LPTSTR aBuf, LPTSTR aVarName); VarSizeType BIV_PtrSize(LPTSTR aBuf, LPTSTR aVarName); //////////////////////// // BUILT-IN FUNCTIONS // //////////////////////// // Caller has ensured that SYM_VAR's Type() is VAR_NORMAL and that it's either not an environment // variable or the caller wants environment variables treated as having zero length. #define EXPR_TOKEN_LENGTH(token_raw, token_as_string) \ ( (token_raw->symbol == SYM_VAR && !token_raw->var->IsBinaryClip()) \ ? token_raw->var->Length()\ : _tcslen(token_as_string) ) #ifdef ENABLE_DLLCALL bool IsDllArgTypeName(LPTSTR name); void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free = NULL); BIF_DECL(BIF_DllCall); BIF_DECL(BIF_DynaCall); #endif BIF_DECL(BIF_FindFunc); BIF_DECL(BIF_FindLabel); BIF_DECL(BIF_Getvar); BIF_DECL(BIF_Static) ; BIF_DECL(BIF_Alias) ; BIF_DECL(BIF_CacheEnable) ; BIF_DECL(BIF_getTokenValue) ; BIF_DECL(BIF_ResourceLoadLibrary); BIF_DECL(BIF_MemoryLoadLibrary); BIF_DECL(BIF_MemoryGetProcAddress); BIF_DECL(BIF_MemoryFreeLibrary); BIF_DECL(BIF_Lock); BIF_DECL(BIF_TryLock); BIF_DECL(BIF_UnLock); BIF_DECL(BIF_StrLen); BIF_DECL(BIF_SubStr); BIF_DECL(BIF_InStr); BIF_DECL(BIF_RegEx); BIF_DECL(BIF_Asc); BIF_DECL(BIF_Chr); BIF_DECL(BIF_NumGet); BIF_DECL(BIF_NumPut); BIF_DECL(BIF_StrGetPut); BIF_DECL(BIF_IsLabel); BIF_DECL(BIF_IsFunc); BIF_DECL(BIF_Func); BIF_DECL(BIF_IsByRef); BIF_DECL(BIF_GetKeyState); BIF_DECL(BIF_GetKeyName); BIF_DECL(BIF_VarSetCapacity); BIF_DECL(BIF_FileExist); BIF_DECL(BIF_WinExistActive); BIF_DECL(BIF_Round); BIF_DECL(BIF_FloorCeil); 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_Exp); BIF_DECL(BIF_SqrtLogLn); BIF_DECL(BIF_OnMessage); #ifdef ENABLE_REGISTERCALLBACK BIF_DECL(BIF_RegisterCallback); #endif #ifndef MINIDLL BIF_DECL(BIF_StatusBar); BIF_DECL(BIF_LV_GetNextOrCount); BIF_DECL(BIF_LV_GetText); BIF_DECL(BIF_LV_AddInsertModify); BIF_DECL(BIF_LV_Delete); BIF_DECL(BIF_LV_InsertModifyDeleteCol); BIF_DECL(BIF_LV_SetImageList); BIF_DECL(BIF_TV_AddModifyDelete); BIF_DECL(BIF_TV_GetRelatedItem); BIF_DECL(BIF_TV_Get); BIF_DECL(BIF_TV_SetImageList); BIF_DECL(BIF_IL_Create); BIF_DECL(BIF_IL_Destroy); BIF_DECL(BIF_IL_Add); #endif BIF_DECL(BIF_Trim); // L31: Also handles LTrim and RTrim. BIF_DECL(BIF_IsObject); BIF_DECL(BIF_ObjCreate); BIF_DECL(BIF_ObjArray); BIF_DECL(BIF_CriticalObject); BIF_DECL(BIF_ObjInvoke); // Pseudo-operator. See script_object.cpp for comments. BIF_DECL(BIF_ObjGetInPlace); // Pseudo-operator. BIF_DECL(BIF_ObjNew); // Pseudo-operator. BIF_DECL(BIF_ObjIncDec); // Pseudo-operator. BIF_DECL(BIF_ObjAddRefRelease); // 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_ObjInsert); BIF_DECL(BIF_ObjRemove); BIF_DECL(BIF_ObjGetCapacity); BIF_DECL(BIF_ObjSetCapacity); BIF_DECL(BIF_ObjGetAddress); BIF_DECL(BIF_ObjMaxIndex); BIF_DECL(BIF_ObjMinIndex); BIF_DECL(BIF_ObjNewEnum); BIF_DECL(BIF_ObjHasKey); BIF_DECL(BIF_ObjClone); // Advanced file IO interfaces BIF_DECL(BIF_FileOpen); BIF_DECL(BIF_ComObjActive); BIF_DECL(BIF_ComObjCreate); BIF_DECL(BIF_ComObjGet); +BIF_DECL(BIF_ComObjMemDll); +BIF_DECL(BIF_ComObjDll); BIF_DECL(BIF_ComObjConnect); BIF_DECL(BIF_ComObjError); BIF_DECL(BIF_ComObjTypeOrValue); BIF_DECL(BIF_ComObjFlags); BIF_DECL(BIF_ComObjArray); BIF_DECL(BIF_ComObjQuery); BIF_DECL(BIF_Exception); BOOL LegacyResultToBOOL(LPTSTR aResult); BOOL LegacyVarToBOOL(Var &aVar); BOOL TokenToBOOL(ExprTokenType &aToken, SymbolType aTokenIsNumber); SymbolType TokenIsPureNumeric(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken); BOOL TokenIsEmptyString(ExprTokenType &aToken, BOOL aWarnUninitializedVar); // Same as TokenIsEmptyString but optionally warns if the token is an uninitialized var. __int64 TokenToInt64(ExprTokenType &aToken, BOOL aIsPureInteger = FALSE); double TokenToDouble(ExprTokenType &aToken, BOOL aCheckForHex = TRUE, BOOL aIsPureFloat = FALSE); LPTSTR TokenToString(ExprTokenType &aToken, LPTSTR aBuf = NULL); ResultType TokenToDoubleOrInt64(ExprTokenType &aToken); IObject *TokenToObject(ExprTokenType &aToken); // L31 Func *TokenToFunc(ExprTokenType &aToken); ResultType TokenSetResult(ExprTokenType &aResultToken, LPCTSTR aResult, size_t aResultLength = -1); LPTSTR RegExMatch(LPTSTR aHaystack, LPTSTR aNeedleRegEx); void SetWorkingDir(LPTSTR aNewDir); int ConvertJoy(LPTSTR aBuf, int *aJoystickID = NULL, bool aAllowOnlyButtons = false); bool ScriptGetKeyState(vk_type aVK, KeyStateTypes aKeyStateType); double ScriptGetJoyState(JoyControls aJoy, int aJoystickID, ExprTokenType &aToken, bool aUseBoolForUpDown); #endif diff --git a/source/script_com.cpp b/source/script_com.cpp index 0586589..eb2e32c 100644 --- a/source/script_com.cpp +++ b/source/script_com.cpp @@ -1,563 +1,651 @@ #include "stdafx.h" #include "globaldata.h" #include "script.h" #include "script_object.h" #include "script_com.h" - - +#include "MemoryModule.h" // IID__IObject -- .NET's System.Object: const IID IID__Object = {0x65074F7F, 0x63C0, 0x304E, 0xAF, 0x0A, 0xD5, 0x17, 0x41, 0xCB, 0x4A, 0x8D}; BIF_DECL(BIF_ComObjCreate) { HRESULT hr; CLSID clsid, iid; for (;;) { hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[0])), &clsid); if (FAILED(hr)) break; if (aParamCount > 1) { hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[1])), &iid); if (FAILED(hr)) break; IUnknown *punk; hr = CoCreateInstance(clsid, NULL, CLSCTX_SERVER, iid, (void **)&punk); if (FAILED(hr)) break; // Return interface pointer, as requested. aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64)punk; } else { IDispatch *pdisp; hr = CoCreateInstance(clsid, NULL, CLSCTX_SERVER, IID_IDispatch, (void **)&pdisp); if (FAILED(hr)) break; // Return dispatchable object. if ( !(aResultToken.object = new ComObject(pdisp)) ) break; aResultToken.symbol = SYM_OBJECT; } return; } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ComError(hr); } +BIF_DECL(BIF_ComObjMemDll) +{ // ComObjMemDll(MemoryModuleHandle,CLSID) + if ((aParam[0]->symbol != SYM_INTEGER && aParam[0]->symbol != SYM_VAR) + || (aParam[1]->symbol != SYM_STRING && aParam[1]->symbol != SYM_VAR)) + { + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; // simply exit + } + HMEMORYMODULE hDLL = (HMEMORYMODULE)TokenToInt64(*aParam[0]); + + typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); + pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(hDLL,"DllGetClassObject"); + IClassFactory* pClassFactory = NULL; + CLSID clsid; + CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[1])), &clsid); + HRESULT hr; + hr = GetClassObject(clsid, IID_IClassFactory, (LPVOID*)&pClassFactory); + if(FAILED(hr)){ + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; + } + IDispatch *pdisp; + hr = pClassFactory->CreateInstance(NULL, IID_IUnknown, (void**)&pdisp); + pClassFactory->Release(); + if(FAILED(hr)) + { + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; + } + if (aResultToken.object = new ComObject(pdisp)) + { + aResultToken.symbol = SYM_OBJECT; + return; + } + pdisp->Release(); + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); +} + +BIF_DECL(BIF_ComObjDll) +{ // ComObjDll(moduleHandle,CLSID) + if ((aParam[0]->symbol != SYM_INTEGER && aParam[0]->symbol != SYM_VAR) + || (aParam[1]->symbol != SYM_STRING && aParam[1]->symbol != SYM_VAR)) + { + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; // simply exit + } + HMODULE hDLL = (HMODULE)TokenToInt64(*aParam[0]); + + typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); + pDllGetClassObject GetClassObject = (pDllGetClassObject)::GetProcAddress(hDLL,"DllGetClassObject"); + IClassFactory* pClassFactory = NULL; + CLSID clsid; + CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[1])), &clsid); + HRESULT hr; + hr = GetClassObject(clsid, IID_IClassFactory, (LPVOID*)&pClassFactory); + if(FAILED(hr)){ + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; + } + IDispatch *pdisp; + hr = pClassFactory->CreateInstance(NULL, IID_IUnknown, (void**)&pdisp); + pClassFactory->Release(); + if(FAILED(hr)) + { + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); + return; + } + if (aResultToken.object = new ComObject(pdisp)) + { + aResultToken.symbol = SYM_OBJECT; + return; + } + pdisp->Release(); + ComError(hr); + aResultToken.symbol = SYM_STRING; + aResultToken.marker = _T(""); +} BIF_DECL(BIF_ComObjGet) { HRESULT hr; IDispatch *pdisp; hr = CoGetObject(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[0])), NULL, IID_IDispatch, (void **)&pdisp); if (SUCCEEDED(hr)) { if (aResultToken.object = new ComObject(pdisp)) { aResultToken.symbol = SYM_OBJECT; return; } pdisp->Release(); } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ComError(hr); } BIF_DECL(BIF_ComObjActive) { if (!aParamCount) // ComObjMissing() { SafeSetTokenObject(aResultToken, new ComObject(DISP_E_PARAMNOTFOUND, VT_ERROR)); return; } aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); ComObject *obj; if (TokenIsPureNumeric(*aParam[0])) { VARTYPE vt; __int64 llVal; USHORT flags = 0; if (aParamCount > 1) { // ComObj(vt, value [, flags]) vt = (VARTYPE)TokenToInt64(*aParam[0]); llVal = TokenToInt64(*aParam[1]); if (aParamCount > 2) flags = (USHORT)TokenToInt64(*aParam[2]); } else { // ComObj(pdisp) vt = VT_DISPATCH; llVal = TokenToInt64(*aParam[0]); } if (vt == VT_DISPATCH || vt == VT_UNKNOWN) { IUnknown *punk = (IUnknown *)llVal; if (punk) { if (aParamCount == 1) // Implies above set vt = VT_DISPATCH. { IDispatch *pdisp; if (SUCCEEDED(punk->QueryInterface(IID_IDispatch, (void **)&pdisp))) { // Replace caller-specified interface pointer with pdisp. If caller // has requested we take responsibility for freeing it, do that now: if (flags & ComObject::F_OWNVALUE) punk->Release(); flags |= ComObject::F_OWNVALUE; // Don't AddRef() below since we own this reference. llVal = (__int64)pdisp; } // Otherwise interpret it as IDispatch anyway, since caller has requested it and // there are known cases where it works (such as some CLR COM callable wrappers). } if ( !(flags & ComObject::F_OWNVALUE) ) punk->AddRef(); // "Copy" caller's reference. // Otherwise caller (or above) indicated the object now owns this reference. } // Otherwise, NULL may have some meaning, so allow it. If the // script tries to invoke the object, it'll get a warning then. } if (obj = new ComObject(llVal, vt, flags)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; } else if (vt == VT_DISPATCH || vt == VT_UNKNOWN) ((IUnknown *)llVal)->Release(); } else if (obj = dynamic_cast<ComObject *>(TokenToObject(*aParam[0]))) { if (aParamCount > 1) { // For backward-compatibility: aResultToken.symbol = SYM_INTEGER; aResultToken.marker = _T("ComObjType"); BIF_ComObjTypeOrValue(aResult, aResultToken, aParam, aParamCount); } else if (VT_DISPATCH == obj->mVarType) { aResultToken.symbol = SYM_INTEGER; aResultToken.value_int64 = (__int64) obj->mDispatch; // mDispatch vs mVal64 ensures we zero the high 32 bits in 32-bit builds. if (obj->mDispatch) obj->mDispatch->AddRef(); } } else { HRESULT hr; CLSID clsid; IUnknown *punk; hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[0])), &clsid); if (SUCCEEDED(hr)) { hr = GetActiveObject(clsid, NULL, &punk); if (SUCCEEDED(hr)) { IDispatch *pdisp; if (SUCCEEDED(punk->QueryInterface(IID_IDispatch, (void **)&pdisp))) { if (obj = new ComObject(pdisp)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; } else pdisp->Release(); } punk->Release(); return; } } ComError(hr); } } BIF_DECL(BIF_ComObjConnect) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); if (ComObject *obj = dynamic_cast<ComObject *>(TokenToObject(*aParam[0]))) { if (!obj->mEventSink && VT_DISPATCH == obj->mVarType && obj->mDispatch) { ITypeLib *ptlib; ITypeInfo *ptinfo; TYPEATTR *typeattr; IID iid; BOOL found = false; if (SUCCEEDED(obj->mDispatch->GetTypeInfo(0, LOCALE_USER_DEFAULT, &ptinfo))) { UINT index; if (SUCCEEDED(ptinfo->GetTypeAttr(&typeattr))) { iid = typeattr->guid; ptinfo->ReleaseTypeAttr(typeattr); found = SUCCEEDED(ptinfo->GetContainingTypeLib(&ptlib, &index)); } ptinfo->Release(); } if (found) { found = false; UINT ctinfo = ptlib->GetTypeInfoCount(); for (UINT i = 0; i < ctinfo; i++) { TYPEKIND typekind; if (FAILED(ptlib->GetTypeInfoType(i, &typekind)) || typekind != TKIND_COCLASS || FAILED(ptlib->GetTypeInfo(i, &ptinfo))) continue; WORD cImplTypes = 0; if (SUCCEEDED(ptinfo->GetTypeAttr(&typeattr))) { cImplTypes = typeattr->cImplTypes; ptinfo->ReleaseTypeAttr(typeattr); } for (UINT j = 0; j < cImplTypes; j++) { INT flags; if (SUCCEEDED(ptinfo->GetImplTypeFlags(j, &flags)) && flags == IMPLTYPEFLAG_FDEFAULT) { HREFTYPE reftype; ITypeInfo *prinfo; if (SUCCEEDED(ptinfo->GetRefTypeOfImplType(j, &reftype)) && SUCCEEDED(ptinfo->GetRefTypeInfo(reftype, &prinfo))) { if (SUCCEEDED(prinfo->GetTypeAttr(&typeattr))) { found = iid == typeattr->guid; prinfo->ReleaseTypeAttr(typeattr); } prinfo->Release(); } break; } } if (found) break; ptinfo->Release(); } ptlib->Release(); } if (found) { WORD cImplTypes = 0; if (SUCCEEDED(ptinfo->GetTypeAttr(&typeattr))) { cImplTypes = typeattr->cImplTypes; ptinfo->ReleaseTypeAttr(typeattr); } for(UINT j = 0; j < cImplTypes; j++) { INT flags; HREFTYPE reftype; ITypeInfo *prinfo; if (SUCCEEDED(ptinfo->GetImplTypeFlags(j, &flags)) && flags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE) && SUCCEEDED(ptinfo->GetRefTypeOfImplType(j, &reftype)) && SUCCEEDED(ptinfo->GetRefTypeInfo(reftype, &prinfo))) { if (SUCCEEDED(prinfo->GetTypeAttr(&typeattr))) { if (typeattr->typekind == TKIND_DISPATCH) { obj->mEventSink = new ComEvent(obj, prinfo, typeattr->guid); prinfo->ReleaseTypeAttr(typeattr); break; } prinfo->ReleaseTypeAttr(typeattr); } prinfo->Release(); } } ptinfo->Release(); } } if (obj->mEventSink) { if (aParamCount < 2) obj->mEventSink->Connect(); // Disconnect. else obj->mEventSink->Connect(TokenToString(*aParam[1]), TokenToObject(*aParam[1])); return; } ComError(E_NOINTERFACE); } else ComError(-1); // "No COM object" } BIF_DECL(BIF_ComObjError) { aResultToken.value_int64 = g_ComErrorNotify; if (aParamCount && TokenIsPureNumeric(*aParam[0])) g_ComErrorNotify = (TokenToInt64(*aParam[0]) != 0); } BIF_DECL(BIF_ComObjTypeOrValue) { ComObject *obj = dynamic_cast<ComObject *>(TokenToObject(*aParam[0])); if (!obj) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (ctoupper(aResultToken.marker[6]) == 'V') { aResultToken.value_int64 = obj->mVal64; } else { if (aParamCount < 2) { aResultToken.value_int64 = obj->mVarType; } else { aResultToken.symbol = SYM_STRING; // for all code paths below aResultToken.marker = _T(""); // in case of error ITypeInfo *ptinfo; if (VT_DISPATCH == obj->mVarType && obj->mDispatch && SUCCEEDED(obj->mDispatch->GetTypeInfo(0, LOCALE_USER_DEFAULT, &ptinfo))) { LPTSTR requested_info = TokenToString(*aParam[1]); if (!_tcsicmp(requested_info, _T("name"))) { BSTR name; if (SUCCEEDED(ptinfo->GetDocumentation(MEMBERID_NIL, &name, NULL, NULL, NULL))) { TokenSetResult(aResultToken, CStringTCharFromWCharIfNeeded(name), SysStringLen(name)); SysFreeString(name); } } else if (!_tcsicmp(requested_info, _T("iid"))) { TYPEATTR *typeattr; if (SUCCEEDED(ptinfo->GetTypeAttr(&typeattr))) { aResultToken.marker = aResultToken.buf; #ifdef UNICODE StringFromGUID2(typeattr->guid, aResultToken.marker, MAX_NUMBER_SIZE); #else WCHAR cnvbuf[MAX_NUMBER_SIZE]; StringFromGUID2(typeattr->guid, cnvbuf, MAX_NUMBER_SIZE); CStringCharFromWChar cnvstring(cnvbuf); strncpy(aResultToken.marker, cnvstring.GetBuffer(), MAX_NUMBER_SIZE); #endif ptinfo->ReleaseTypeAttr(typeattr); } } ptinfo->Release(); } } } } BIF_DECL(BIF_ComObjFlags) { ComObject *obj = dynamic_cast<ComObject *>(TokenToObject(*aParam[0])); if (!obj) { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); return; } if (aParamCount > 1) { USHORT flags, mask; if (aParamCount > 2) { flags = (USHORT)TokenToInt64(*aParam[1]); mask = (USHORT)TokenToInt64(*aParam[2]); } else { __int64 bigflags = TokenToInt64(*aParam[1]); if (bigflags < 0) { // Remove specified -flags. flags = 0; mask = (USHORT)-bigflags; } else { // Add only specified flags. flags = (USHORT)bigflags; mask = flags; } } obj->mFlags = (obj->mFlags & ~mask) | (flags & mask); } aResultToken.value_int64 = obj->mFlags; } BIF_DECL(BIF_ComObjArray) { VARTYPE vt = (VARTYPE)TokenToInt64(*aParam[0]); SAFEARRAYBOUND bound[8]; // Same limit as ComObject::SafeArrayInvoke(). int dims = aParamCount - 1; ASSERT(dims <= _countof(bound)); // Prior validation should ensure aParamCount-1 never exceeds 8. for (int i = 0; i < dims; ++i) { bound[i].cElements = (ULONG)TokenToInt64(*aParam[i + 1]); bound[i].lLbound = 0; } SAFEARRAY *psa = SafeArrayCreate(vt, dims, bound); if (!SafeSetTokenObject(aResultToken, psa ? new ComObject((__int64)psa, VT_ARRAY | vt, ComObject::F_OWNVALUE) : NULL) && psa) SafeArrayDestroy(psa); } BIF_DECL(BIF_ComObjQuery) { IUnknown *punk = NULL; ComObject *obj; HRESULT hr; aResultToken.value_int64 = 0; // Set default; on 32-bit builds, only the low 32 bits may be set below. if (obj = dynamic_cast<ComObject *>(TokenToObject(*aParam[0]))) { // We were passed a ComObject, but does it contain an interface pointer? if (obj->mVarType == VT_UNKNOWN || obj->mVarType == VT_DISPATCH) punk = obj->mUnknown; } if (!punk) { // Since it wasn't a valid ComObject, it should be a raw interface pointer. punk = (IUnknown *)TokenToInt64(*aParam[0]); if (punk < (IUnknown *)65536) // Error-detection: the first 64KB of address space is always invalid. { g->LastError = E_INVALIDARG; // For consistency. ComError(-1); return; } } if (aParamCount > 2) // QueryService(obj, SID, IID) { GUID sid, iid; if ( SUCCEEDED(hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[1])), &sid)) && SUCCEEDED(hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[2])), &iid)) ) { IServiceProvider *pprov; if (SUCCEEDED(hr = punk->QueryInterface<IServiceProvider>(&pprov))) { hr = pprov->QueryService(sid, iid, (void **)&aResultToken.value_int64); } } } else // QueryInterface(obj, IID) { GUID iid; if (SUCCEEDED(hr = CLSIDFromString(CStringWCharFromTCharIfNeeded(TokenToString(*aParam[1])), &iid))) { hr = punk->QueryInterface(iid, (void **)&aResultToken.value_int64); } } g->LastError = hr; } bool SafeSetTokenObject(ExprTokenType &aToken, IObject *aObject) { if (aObject) { aToken.symbol = SYM_OBJECT; aToken.object = aObject; return true; } else { aToken.symbol = SYM_STRING; aToken.marker = _T(""); aToken.mem_to_free = NULL; // Only needed for some callers. return false; } } void VariantToToken(VARIANT &aVar, ExprTokenType &aToken, bool aRetainVar = true) { switch (aVar.vt) { case VT_BSTR: aToken.symbol = SYM_STRING; aToken.marker = _T(""); // Set defaults. aToken.mem_to_free = NULL; // size_t len; if (len = SysStringLen(aVar.bstrVal)) { #ifdef UNICODE if (aRetainVar) { // It's safe to pass back the actual BSTR from aVar in this case. aToken.marker = aVar.bstrVal; } // Allocate some memory to pass back to caller: else if (aToken.mem_to_free = tmalloc(len + 1)) { aToken.marker = aToken.mem_to_free; aToken.marker_length = len; tmemcpy(aToken.marker, aVar.bstrVal, len + 1); // +1 for null-terminator } #else CStringCharFromWChar buf(aVar.bstrVal, len); len = buf.GetLength(); // Get ANSI length. if (aToken.mem_to_free = buf.DetachBuffer()) { aToken.marker = aToken.mem_to_free; aToken.marker_length = len; } #endif } if (!aRetainVar) VariantClear(&aVar); break; case VT_I4: case VT_ERROR: aToken.symbol = SYM_INTEGER; aToken.value_int64 = aVar.lVal; break; case VT_I2: case VT_BOOL: aToken.symbol = SYM_INTEGER; aToken.value_int64 = aVar.iVal; break; case VT_R8: aToken.symbol = SYM_FLOAT; aToken.value_double = aVar.dblVal; break; case VT_R4: aToken.symbol = SYM_FLOAT; aToken.value_double = (double)aVar.fltVal;
tinku99/ahkdll
748db261163c10fb474fcba9cb464bea0d3aa768
Another fix for Input when variable is set blank by script
diff --git a/source/script2.cpp b/source/script2.cpp index cd7ccf8..b5492f4 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -1224,1035 +1224,1039 @@ end_get_length: case 0x20AC: SET_HTML_ENTITY("&euro;"); goto end_set_entity; case 0x2122: SET_HTML_ENTITY("&trade;"); goto end_set_entity; default: if (*ucp >= 0xA0 && *ucp <= 0xFF) { *contents++ = '&'; _tcscpy(contents, sHtml[*ucp - 0xA0]); contents += _tcslen(contents); *contents++ = ';'; goto end_set_entity; } // else handled by the following break; } // switch (*ucp) } // if (aFlags & TRANS_HTML_NAMED) if (aFlags & TRANS_HTML_NUMBERED) contents += _stprintf(contents, _T("&#%d;"), (int) *ucp); else *contents++ = *ucp; end_set_entity: ; // prevents compilation error #else *contents++ = '&'; // v1.0.40.02 _tcscpy(contents, sHtml[*ucp - 0x80]); contents += _tcslen(contents); // Added as a fix in v1.0.41 (broken in v1.0.40.02). *contents++ = ';'; // v1.0.40.02 #endif } else *contents++ = *ucp; } #undef SET_HTML_ENTITY } *contents = '\0'; // Terminate the string. return output_var.Close(); // Must be called after Assign(NULL, ...) or when Contents() has been altered because it updates the variable's attributes and properly handles VAR_CLIPBOARD. } case TRANS_CMD_MOD: if ( !(value_double2 = ATOF(aValue2)) ) // Divide by zero, set it to be blank to indicate the problem. return output_var.Assign(); // Otherwise: result_double = qmathFmod(ATOF(aValue1), value_double2); ASSIGN_BASED_ON_TYPE case TRANS_CMD_POW: { // v1.0.44.11: With Laszlo's help, negative bases are now supported as long as the exponent is not fractional. // See SYM_POWER in script_expression.cpp for similar code and more comments. value_double1 = ATOF(aValue1); value_double2 = ATOF(aValue2); bool value1_was_negative = (value_double1 < 0); if (value_double1 == 0.0 && value_double2 < 0 // In essence, this is divide-by-zero. || value1_was_negative && qmathFmod(value_double2, 1.0) != 0.0) // Negative base but exponent isn't close enough to being an integer: unsupported (to simplify code). return output_var.Assign(); // Return a consistent result (blank) rather than something that varies. // Otherwise: if (value1_was_negative) value_double1 = -value_double1; // Force a positive due to the limitations of qmathPow(). result_double = qmathPow(value_double1, value_double2); if (value1_was_negative && qmathFabs(qmathFmod(value_double2, 2.0)) == 1.0) // Negative base and exactly-odd exponent (otherwise, it can only be zero or even because if not it would have returned higher above). result_double = -result_double; ASSIGN_BASED_ON_TYPE_POW } case TRANS_CMD_EXP: return output_var.Assign(qmathExp(ATOF(aValue1))); case TRANS_CMD_SQRT: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathSqrt(value_double1)); case TRANS_CMD_LOG: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathLog10(ATOF(aValue1))); case TRANS_CMD_LN: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathLog(ATOF(aValue1))); case TRANS_CMD_ROUND: // In the future, a string conversion algorithm might be better to avoid the loss // of 64-bit integer precision that it currently caused by the use of doubles in // the calculation: value32 = ATOI(aValue2); multiplier = *aValue2 ? qmathPow(10, value32) : 1; value_double1 = ATOF(aValue1); result_double = (value_double1 >= 0.0 ? qmathFloor(value_double1 * multiplier + 0.5) : qmathCeil(value_double1 * multiplier - 0.5)) / multiplier; ASSIGN_BASED_ON_TYPE_SINGLE_ROUND case TRANS_CMD_CEIL: case TRANS_CMD_FLOOR: // The code here is similar to that in BIF_FloorCeil(), so maintain them together. result_double = ATOF(aValue1); result_double = (trans_cmd == TRANS_CMD_FLOOR) ? qmathFloor(result_double) : qmathCeil(result_double); return output_var.Assign((__int64)(result_double + (result_double > 0 ? 0.2 : -0.2))); // Fixed for v1.0.40.05: See comments in BIF_FloorCeil() for details. case TRANS_CMD_ABS: { // Seems better to convert as string to avoid loss of 64-bit integer precision // that would be caused by conversion to double. I think this will work even // for negative hex numbers that are close to the 64-bit limit since they too have // a minus sign when generated by the script (e.g. -0x1). //result_double = qmathFabs(ATOF(aValue1)); //ASSIGN_BASED_ON_TYPE_SINGLE LPTSTR cp = omit_leading_whitespace(aValue1); // i.e. caller doesn't have to have ltrimmed it. if (*cp == '-') return output_var.Assign(cp + 1); // Omit the first minus sign (simple conversion only). // Otherwise, no minus sign, so just omit the leading whitespace for consistency: return output_var.Assign(cp); } case TRANS_CMD_SIN: return output_var.Assign(qmathSin(ATOF(aValue1))); case TRANS_CMD_COS: return output_var.Assign(qmathCos(ATOF(aValue1))); case TRANS_CMD_TAN: return output_var.Assign(qmathTan(ATOF(aValue1))); case TRANS_CMD_ASIN: value_double1 = ATOF(aValue1); if (value_double1 > 1 || value_double1 < -1) return output_var.Assign(); // ASin and ACos aren't defined for other values. return output_var.Assign(qmathAsin(ATOF(aValue1))); case TRANS_CMD_ACOS: value_double1 = ATOF(aValue1); if (value_double1 > 1 || value_double1 < -1) return output_var.Assign(); // ASin and ACos aren't defined for other values. return output_var.Assign(qmathAcos(ATOF(aValue1))); case TRANS_CMD_ATAN: return output_var.Assign(qmathAtan(ATOF(aValue1))); // For all of the below bitwise operations: // Seems better to convert to signed rather than unsigned so that signed values can // be supported. i.e. it seems better to trade one bit in capacity in order to support // negative numbers. Another reason is that commands such as IfEquals use ATOI64 (signed), // so if we were to produce unsigned 64 bit values here, they would be somewhat incompatible // with other script operations. case TRANS_CMD_BITAND: return output_var.Assign(ATOI64(aValue1) & ATOI64(aValue2)); case TRANS_CMD_BITOR: return output_var.Assign(ATOI64(aValue1) | ATOI64(aValue2)); case TRANS_CMD_BITXOR: return output_var.Assign(ATOI64(aValue1) ^ ATOI64(aValue2)); case TRANS_CMD_BITNOT: value64 = ATOI64(aValue1); if (value64 < 0 || value64 > UINT_MAX) // Treat it as a 64-bit signed value, since no other aspects of the program // (e.g. IfEqual) will recognize an unsigned 64 bit number. return output_var.Assign(~value64); else // Treat it as a 32-bit unsigned value when inverting and assigning. This is // because assigning it as a signed value would "convert" it into a 64-bit // value, which in turn is caused by the fact that the script sees all negative // numbers as 64-bit values (e.g. -1 is 0xFFFFFFFFFFFFFFFF). return output_var.Assign(~(DWORD)value64); case TRANS_CMD_BITSHIFTLEFT: // Equivalent to multiplying by 2^value2 return output_var.Assign(ATOI64(aValue1) << ATOI(aValue2)); case TRANS_CMD_BITSHIFTRIGHT: // Equivalent to dividing (integer) by 2^value2 return output_var.Assign(ATOI64(aValue1) >> ATOI(aValue2)); } return FAIL; // Never executed (increases maintainability and avoids compiler warning). } #ifndef MINIDLL ResultType Line::Input() // OVERVIEW: // Although a script can have many concurrent quasi-threads, there can only be one input // at a time. Thus, if an input is ongoing and a new thread starts, and it begins its // own input, that input should terminate the prior input prior to beginning the new one. // In a "worst case" scenario, each interrupted quasi-thread could have its own // input, which is in turn terminated by the thread that interrupts it. Every time // this function returns, it must be sure to set g_input.status to INPUT_OFF beforehand. // This signals the quasi-threads beneath, when they finally return, that their input // was terminated due to a new input that took precedence. { if (g_os.IsWin9x()) // v1.0.44.14: For simplicity, do nothing on Win9x rather than try to see if it actually supports the hook (such as if its some kind of emulated/hybrid OS). return OK; // Could also set ErrorLevel to "Timeout" and output_var to be blank, but the benefits to backward compatibility seemed too dubious. // Since other script threads can interrupt this command while it's running, 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. Var *output_var = OUTPUT_VAR; // See comment above. if (!output_var) { // No output variable, which due to load-time validation means there are no other args either. // This means that the user is specifically canceling the prior input (if any). Thus, our // ErrorLevel here is set to 1 or 0, but the prior input's ErrorLevel will be set to "NewInput" // when its quasi-thread is resumed: bool prior_input_is_being_terminated = (g_input.status == INPUT_IN_PROGRESS); g_input.status = INPUT_OFF; return SetErrorLevelOrThrowBool(!prior_input_is_being_terminated); // Above: It's considered an "error" of sorts when there is no prior input to terminate. } // Below are done directly this way rather than passed in as args mainly to emphasize that // ArgLength() can safely be called in Line methods like this one (which is done further below). // It also may also slightly improve performance and reduce code size. LPTSTR aOptions = ARG2, aEndKeys = ARG3, aMatchList = ARG4; // The aEndKeys string must be modifiable (not constant), since for performance reasons, // it's allowed to be temporarily altered by this function. // Set default in case of early return (we want these to be in effect even if // FAIL is returned for our thread, since the underlying thread that had the // active input prior to us didn't fail and it it needs to know how its input // was terminated): g_input.status = INPUT_OFF; ////////////////////////////////////////////// // Set up sparse arrays according to aEndKeys: ////////////////////////////////////////////// UCHAR end_vk[VK_ARRAY_COUNT] = {0}; // A sparse array that indicates which VKs terminate the input. UCHAR end_sc[SC_ARRAY_COUNT] = {0}; // A sparse array that indicates which SCs terminate the input. vk_type vk; sc_type sc = 0; modLR_type modifiersLR; size_t key_text_length; TCHAR *end_pos, single_char_string[2]; single_char_string[1] = '\0'; // Init its second character once, since the loop only changes the first char. for (; *aEndKeys; ++aEndKeys) // 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 (*aEndKeys) { case '}': continue; // Important that these be ignored. case '{': { if ( !(end_pos = _tcschr(aEndKeys + 1, '}')) ) continue; // Do nothing, just ignore the unclosed '{' and continue. if ( !(key_text_length = end_pos - aEndKeys - 1) ) { 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. } *end_pos = '\0'; // temporarily terminate the string here. // v1.0.45: Fixed this section to differentiate between } and ] (and also { and [, as well as // anything else enclosed in {} that requires END_KEY_WITH_SHIFT/END_KEY_WITHOUT_SHIFT consideration. modifiersLR = 0; // Init prior to below. if (vk = TextToVK(aEndKeys + 1, &modifiersLR, true)) { if (key_text_length == 1) *single_char_string = aEndKeys[1]; //else leave it at its default of "not a single-char key-name". } else // No virtual key, so try to find a scan code. if (sc = TextToSC(aEndKeys + 1)) end_sc[sc] = END_KEY_ENABLED; *end_pos = '}'; // undo the temporary termination aEndKeys = end_pos; // In prep for aEndKeys++ at the bottom of the loop. break; // Break out of the switch() and do the vk handling beneath it (if there is a vk). } default: *single_char_string = *aEndKeys; modifiersLR = 0; // Init prior to below. vk = TextToVK(single_char_string, &modifiersLR, true); } // switch() if (vk) // A valid virtual key code was discovered above. { end_vk[vk] |= END_KEY_ENABLED; // Use of |= is essential for cases such as ";:". // Insist the shift key be down to form genuinely different symbols -- // namely punctuation marks -- but not for alphabetic chars. In the // future, an option can be added to the Options param to treat // end chars as case sensitive (if there is any demand for that): if (*single_char_string && !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; } } } // for() ///////////////////////////////////////////////// // Parse aMatchList into an array of key phrases: ///////////////////////////////////////////////// LPTSTR *realloc_temp; // Needed since realloc returns NULL on failure but leaves original block allocated. g_input.MatchCount = 0; // Set default. if (*aMatchList) { // If needed, create the array of pointers that points into MatchBuf to each match phrase: if (!g_input.match) { if ( !(g_input.match = (LPTSTR *)malloc(INPUT_ARRAY_BLOCK_SIZE * sizeof(LPTSTR))) ) return LineError(ERR_OUTOFMEM); // Short msg. since so rare. g_input.MatchCountMax = INPUT_ARRAY_BLOCK_SIZE; } // If needed, create or enlarge the buffer that contains all the match phrases: size_t aMatchList_length = ArgLength(4); // Performs better than _tcslen(aMatchList); size_t space_needed = aMatchList_length + 1; // +1 for the final zero terminator. if (space_needed > g_input.MatchBufSize) { g_input.MatchBufSize = (UINT)(space_needed > 4096 ? space_needed : 4096); if (g_input.MatchBuf) // free the old one since it's too small. free(g_input.MatchBuf); if ( !(g_input.MatchBuf = tmalloc(g_input.MatchBufSize)) ) { g_input.MatchBufSize = 0; return LineError(ERR_OUTOFMEM); // Short msg. since so rare. } } // Copy aMatchList into the match buffer: LPTSTR source, dest; for (source = aMatchList, dest = g_input.match[g_input.MatchCount] = g_input.MatchBuf ; *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 (*g_input.match[g_input.MatchCount]) { ++g_input.MatchCount; g_input.match[g_input.MatchCount] = ++dest; *dest = '\0'; // Init to prevent crash on orphaned comma such as "btw,otoh," } if (*(source + 1)) // There is a next element. { if (g_input.MatchCount >= g_input.MatchCountMax) // Rarely needed, so just realloc() to expand. { // Expand the array by one block: if ( !(realloc_temp = (LPTSTR *)realloc(g_input.match // Must use a temp variable. , (g_input.MatchCountMax + INPUT_ARRAY_BLOCK_SIZE) * sizeof(LPTSTR))) ) return LineError(ERR_OUTOFMEM); // Short msg. since so rare. g_input.match = realloc_temp; g_input.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 (*g_input.match[g_input.MatchCount]) // i.e. omit empty strings from the match list. ++g_input.MatchCount; } // Notes about the below macro: // In case the Input timer has already put a WM_TIMER msg in our queue before we killed it, // clean out the queue now to avoid any chance that such a WM_TIMER message will take effect // later when it would be unexpected and might interfere with this input. To avoid an // unnecessary call to PeekMessage(), which has been known to yield our timeslice to other // processes if the CPU is under load (which might be undesirable if this input is // time-critical, such as in a game), call GetQueueStatus() to see if there are any timer // messages in the queue. I believe that GetQueueStatus(), unlike PeekMessage(), does not // have the nasty/undocumented side-effect of yielding our timeslice under certain hard-to-reproduce // circumstances, but Google and MSDN are completely devoid of any confirming info on this. #define KILL_AND_PURGE_INPUT_TIMER \ if (g_InputTimerExists)\ {\ KILL_INPUT_TIMER \ if (HIWORD(GetQueueStatus(QS_TIMER)) & QS_TIMER)\ MsgSleep(-1);\ } // Be sure to get rid of the timer if it exists due to a prior, ongoing input. // It seems best to do this only after signaling the hook to start the input // so that it's MsgSleep(-1), if it launches a new hotkey or timed subroutine, // will be less likely to interrupt us during our setup of the input, i.e. // it seems best that we put the input in progress prior to allowing any // interruption. UPDATE: Must do this before changing to INPUT_IN_PROGRESS // because otherwise the purging of the timer message might call InputTimeout(), // which in turn would set the status immediately to INPUT_TIMED_OUT: KILL_AND_PURGE_INPUT_TIMER ////////////////////////////////////////////////////////////// // Initialize buffers and state variables for use by the hook: ////////////////////////////////////////////////////////////// // Set the defaults that will be in effect unless overridden by an item in aOptions: g_input.BackspaceIsUndo = true; g_input.CaseSensitive = false; g_input.IgnoreAHKInput = false; g_input.TranscribeModifiedKeys = false; g_input.Visible = false; g_input.FindAnywhere = false; int timeout = 0; // Set default. TCHAR input_buf[INPUT_BUFFER_SIZE] = _T(""); // Will contain the actual input from the user. TCHAR prev_buf[INPUT_BUFFER_SIZE] = _T(""); g_input.buffer = input_buf; g_input.BufferLength = 0; g_input.BufferLengthMax = INPUT_BUFFER_SIZE - 1; for (LPTSTR cp = aOptions; *cp; ++cp) { switch(ctoupper(*cp)) { case 'A': if (_tcslen(output_var->Contents())) // Append value if variable is not empty (only strings allowed) { g_input.BufferLength = (int) _tcslen(output_var->Contents()); if (g_input.BufferLength > INPUT_BUFFER_SIZE - 1) g_input.BufferLength = INPUT_BUFFER_SIZE - 1; _tcsncpy(input_buf,output_var->Contents(),g_input.BufferLength); _tcscpy(prev_buf,input_buf); } break; case 'B': g_input.BackspaceIsUndo = false; break; case 'C': g_input.CaseSensitive = true; break; case 'I': g_input.IgnoreAHKInput = true; break; case 'M': g_input.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: g_input.BufferLengthMax = _ttoi(cp + 1); if (g_input.BufferLengthMax > INPUT_BUFFER_SIZE - 1) g_input.BufferLengthMax = INPUT_BUFFER_SIZE - 1; 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': g_input.Visible = true; break; case '*': g_input.FindAnywhere = true; break; } } // Point the global addresses to our memory areas on the stack: g_input.EndVK = end_vk; g_input.EndSC = end_sc; g_input.status = INPUT_IN_PROGRESS; // Signal the hook to start the input. // Make script persistent. This is mostly for backward compatibility because it is documented behavior. // even though as of v1.0.42.03, the keyboard hook does not become permanent (which allows a subsequent // use of the commands Suspend/Hotkey to deinstall it, which seems to add flexibility/benefit). g_persistent = true; Hotkey::InstallKeybdHook(); // Install the hook (if needed). // A timer is used rather than monitoring the elapsed time here directly because // this script's quasi-thread might be interrupted by a Timer or Hotkey subroutine, // which (if it takes a long time) would result in our Input not obeying its timeout. // By using an actual timer, the TimerProc() will run when the timer expires regardless // of which quasi-thread is active, and it will end our input on schedule: if (timeout > 0) SET_INPUT_TIMER(timeout < 10 ? 10 : timeout) ////////////////////////////////////////////////////////////////// // Wait for one of the following to terminate our input: // 1) The hook (due a match in aEndKeys or aMatchList); // 2) A thread that interrupts us with a new Input of its own; // 3) The timer we put in effect for our timeout (if we have one). ////////////////////////////////////////////////////////////////// for (;;) { + int output_var_len; // Rather than monitoring the timeout here, just wait for the incoming WM_TIMER message // to take effect as a TimerProc() call during the MsgSleep(): MsgSleep(); // HotKeyIt added multi-threading support so variable can be read from other threads while input is in progress - if (_tcsncmp(prev_buf,output_var->Contents(),_tcslen(output_var->Contents()) > INPUT_BUFFER_SIZE - 1 ? INPUT_BUFFER_SIZE - 1 : _tcslen(output_var->Contents()))) // Check for vars contents and updatebuffer - { - g_input.BufferLength = (int) _tcslen(output_var->Contents()); - if (g_input.BufferLength > INPUT_BUFFER_SIZE - 1) - g_input.BufferLength = INPUT_BUFFER_SIZE - 1; - _tcsncpy(input_buf,output_var->Contents(),g_input.BufferLength); - _tcscpy(prev_buf,input_buf); + output_var_len = (int) _tcslen(output_var->Contents()); + if (output_var_len > INPUT_BUFFER_SIZE - 1) + output_var_len = INPUT_BUFFER_SIZE - 1; + if (_tcsncmp(prev_buf,output_var->Contents(),output_var_len ? output_var_len : 1)) // Check for vars contents and updatebuffer + { + g_input.BufferLength = output_var_len; + _tcsncpy(input_buf,output_var->Contents(),output_var_len); + input_buf[output_var_len] = '\0'; + _tcsncpy(prev_buf,input_buf,output_var_len); + prev_buf[output_var_len] = '\0'; } else if (_tcscmp(prev_buf,input_buf)) { if (_tcslen(input_buf) || !output_var->CharCapacity()) // Assign will free memory if input_buf empty { output_var->Assign(input_buf); _tcscpy(prev_buf,input_buf); } else { // Assign empty string *output_var->mAliasFor->mCharContents = '\0'; *prev_buf = '\0'; } } if (g_input.status != INPUT_IN_PROGRESS) break; } switch(g_input.status) { case INPUT_TIMED_OUT: g_ErrorLevel->Assign(_T("Timeout")); break; case INPUT_TERMINATED_BY_MATCH: g_ErrorLevel->Assign(_T("Match")); break; case INPUT_TERMINATED_BY_ENDKEY: { TCHAR key_name[128] = _T("EndKey:"); if (g_input.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(g_input.EndingVK, vk_to_sc(g_input.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 + 7, 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 + 7 + count) = '\0'; // Terminate the string. } else g_input.EndedBySC ? SCtoKeyName(g_input.EndingSC, key_name + 7, _countof(key_name) - 7) : VKtoKeyName(g_input.EndingVK, key_name + 7, _countof(key_name) - 7); g_ErrorLevel->Assign(key_name); break; } case INPUT_LIMIT_REACHED: g_ErrorLevel->Assign(_T("Max")); break; default: // Our input was terminated due to a new input in a quasi-thread that interrupted ours. g_ErrorLevel->Assign(_T("NewInput")); break; } g_input.status = INPUT_OFF; // See OVERVIEW above for why this must be set prior to returning. // In case it ended for reason other than a timeout, in which case the timer is still on: KILL_AND_PURGE_INPUT_TIMER // Seems ok to assign after the kill/purge above since input_buf is our own stack variable // and its contents shouldn't be affected even if KILL_AND_PURGE_INPUT_TIMER's MsgSleep() // results in a new thread being created that starts a new Input: if (_tcslen(input_buf) || !output_var->CharCapacity()) // Assign will free memory if input_buf empty return output_var->Assign(input_buf); else { *output_var->mAliasFor->mCharContents = '\0'; // Assign empty string return OK; } } #endif ResultType Line::PerformShowWindow(ActionTypeType aActionType, LPTSTR aTitle, LPTSTR aText , LPTSTR aExcludeTitle, LPTSTR aExcludeText) { // 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 = (aActionType == ACT_WINSHOW && !g->DetectHiddenWindows); if (need_restore) g->DetectHiddenWindows = true; HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (need_restore) g->DetectHiddenWindows = false; if (!target_window) return OK; // WinGroup's EnumParentActUponAll() is quite similar to the following, so the two should be // maintained together. int nCmdShow = SW_NONE; // Set default. switch (aActionType) { // 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 ACT_WINMINIMIZE: if (IsWindowHung(target_window)) { if (g_os.IsWin2000orLater()) nCmdShow = SW_FORCEMINIMIZE; //else it's not Win2k or later. I have confirmed that 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 ACT_WINMAXIMIZE: if (!IsWindowHung(target_window)) nCmdShow = SW_MAXIMIZE; break; case ACT_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 ACT_WINHIDE: nCmdShow = SW_HIDE; break; case ACT_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); //PostMessage(target_window, WM_SYSCOMMAND, SC_MINIMIZE, 0); DoWinDelay; } return OK; // Return success for all the above cases. } ResultType Line::PerformWait() // Since other script threads can interrupt these commands while they're running, it's important that // these commands 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. // fincs: it seems best that this function not throw an exception if the wait timeouts. { bool wait_indefinitely; int sleep_duration; DWORD start_time; vk_type vk; // For GetKeyState. HANDLE running_process; // For RUNWAIT DWORD exit_code; // For RUNWAIT // For ACT_KEYWAIT: bool wait_for_keydown; KeyStateTypes key_state_type; JoyControls joy; int joystick_id; ExprTokenType token; TCHAR buf[LINE_SIZE]; if (mActionType == ACT_RUNWAIT) { bool use_el = tcscasestr(ARG3, _T("UseErrorLevel")); if (!g_script.ActionExec(ARG1, NULL, ARG2, !use_el, ARG3, &running_process, use_el, true, ARGVAR4)) // Load-time validation has ensured that the arg is a valid output variable (e.g. not a built-in var). return use_el ? g_ErrorLevel->Assign(_T("ERROR")) : FAIL; //else fall through to the waiting-phase of the operation. // Above: The special string ERROR is used, rather than a number like 1, because currently // RunWait might in the future be able to return any value, including 259 (STATUS_PENDING). } // Must NOT use ELSE-IF in line below due to ELSE further down needing to execute for RunWait. if (mActionType == ACT_KEYWAIT) { if ( !(vk = TextToVK(ARG1)) ) { if ( !(joy = (JoyControls)ConvertJoy(ARG1, &joystick_id)) ) // Not a valid key name. // Indicate immediate timeout (if timeout was specified) or error. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); if (!IS_JOYSTICK_BUTTON(joy)) // Currently, only buttons are supported. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); } // Set defaults: wait_for_keydown = false; // The default is to wait for the key to be released. key_state_type = KEYSTATE_PHYSICAL; // Since physical is more often used. wait_indefinitely = true; sleep_duration = 0; for (LPTSTR cp = ARG2; *cp; ++cp) { switch(ctoupper(*cp)) { case 'D': wait_for_keydown = true; break; case 'L': key_state_type = KEYSTATE_LOGICAL; 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: wait_indefinitely = false; sleep_duration = (int)(ATOF(cp + 1) * 1000); break; } } // The following must be set for ScriptGetJoyState(): token.symbol = SYM_STRING; token.marker = buf; } else if ( (mActionType != ACT_RUNWAIT && mActionType != ACT_CLIPWAIT && *ARG3) || (mActionType == ACT_CLIPWAIT && *ARG1) ) { // Since the param containing the timeout value isn't blank, it must be numeric, // otherwise, the loading validation would have prevented the script from loading. wait_indefinitely = false; sleep_duration = (int)(ATOF(mActionType == ACT_CLIPWAIT ? ARG1 : ARG3) * 1000); // Can be zero. if (sleep_duration < 1) // Waiting 500ms in place of a "0" seems more useful than a true zero, which // doens't need to be supported because it's the same thing as something like // "IfWinExist". A true zero for clipboard would be the same as // "IfEqual, clipboard, , xxx" (though admittedly it's higher overhead to // actually fetch the contents of the clipboard). sleep_duration = 500; } else { wait_indefinitely = true; sleep_duration = 0; // Just to catch any bugs. } if (mActionType != ACT_RUNWAIT) g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Set default ErrorLevel to be possibly overridden later on. bool any_clipboard_format = (mActionType == ACT_CLIPWAIT && ArgToInt(2) == 1); // Right before starting the wait-loop, make a copy of our args using the stack // space in our recursion layer. This is done in case other hotkey subroutine(s) // are launched while we're waiting here, which might cause our args to be overwritten // if any of them happen to be in the Deref buffer: LPTSTR arg[MAX_ARGS], marker; int i, space_remaining; for (i = 0, space_remaining = LINE_SIZE, marker = buf; i < mArgc; ++i) { if (!space_remaining) // Realistically, should never happen. arg[i] = _T(""); else { arg[i] = marker; // Point it to its place in the buffer. tcslcpy(marker, sArgDeref[i], space_remaining); // Make the copy. marker += _tcslen(marker) + 1; // +1 for the zero terminator of each arg. space_remaining = (int)(LINE_SIZE - (marker - buf)); } } for (start_time = GetTickCount();;) // start_time is initialized unconditionally for use with v1.0.30.02's new logging feature further below. { // Always do the first iteration so that at least one check is done. switch(mActionType) { case ACT_WINWAIT: #define SAVED_WIN_ARGS SAVED_ARG1, SAVED_ARG2, SAVED_ARG4, SAVED_ARG5 if (WinExist(*g, SAVED_WIN_ARGS, false, true)) { DoWinDelay; return OK; } break; case ACT_WINWAITCLOSE: if (!WinExist(*g, SAVED_WIN_ARGS)) { DoWinDelay; return OK; } break; case ACT_WINWAITACTIVE: if (WinActive(*g, SAVED_WIN_ARGS, true)) { DoWinDelay; return OK; } break; case ACT_WINWAITNOTACTIVE: if (!WinActive(*g, SAVED_WIN_ARGS, true)) { DoWinDelay; return OK; } break; case ACT_CLIPWAIT: // Seems best to consider CF_HDROP to be a non-empty clipboard, since we // support the implicit conversion of that format to text: if (any_clipboard_format) { if (CountClipboardFormats()) return OK; } else if (IsClipboardFormatAvailable(CF_NATIVETEXT) || IsClipboardFormatAvailable(CF_HDROP)) return OK; break; case ACT_KEYWAIT: if (vk) // Waiting for key or mouse button, not joystick. { if (ScriptGetKeyState(vk, key_state_type) == wait_for_keydown) return OK; } else // Waiting for joystick button { if ((bool)ScriptGetJoyState(joy, joystick_id, token, false) == wait_for_keydown) return OK; } break; case ACT_RUNWAIT: // Pretty nasty, but for now, nothing is done to prevent an infinite loop. // In the future, maybe OpenProcess() can be used to detect if a process still // exists (is there any other way?): // MSDN: "Warning: If a process happens to return STILL_ACTIVE (259) as an error code, // applications that test for this value could end up in an infinite loop." if (running_process) GetExitCodeProcess(running_process, &exit_code); else // it can be NULL in the case of launching things like "find D:\" or "www.yahoo.com" exit_code = 0; if (exit_code != STATUS_PENDING) // STATUS_PENDING == STILL_ACTIVE { if (running_process) 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: return g_ErrorLevel->Assign((int)exit_code); } break; } // Must cast to int or any negative result will be lost due to DWORD type: if (wait_indefinitely || (int)(sleep_duration - (GetTickCount() - start_time)) > SLEEP_INTERVAL_HALF) { if (MsgSleep(INTERVAL_UNSPECIFIED)) // INTERVAL_UNSPECIFIED performs better. { // 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) { sLog[sLogNext] = this; sLogTick[sLogNext++] = start_time; // Store a special value so that Line::LogToText() can report that its "still waiting" from earlier. if (sLogNext >= LINE_LOG_SIZE) sLogNext = 0; // The lines above are the similar to those used in ExecUntil(), so the two should be // maintained together. } } } else // Done waiting. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Since it timed out, we override the default with this. } // for() } ResultType Line::WinMove(LPTSTR aTitle, LPTSTR aText, LPTSTR aX, LPTSTR aY , LPTSTR aWidth, LPTSTR aHeight, LPTSTR aExcludeTitle, LPTSTR aExcludeText) { // So that compatibility is retained, don't set ErrorLevel for commands that are native to AutoIt2 // but that AutoIt2 doesn't use ErrorLevel with (such as this one). HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) return OK; RECT rect; if (!GetWindowRect(target_window, &rect)) return OK; // Can't set errorlevel, see above. MoveWindow(target_window , *aX && _tcsicmp(aX, _T("default")) ? ATOI(aX) : rect.left // X-position , *aY && _tcsicmp(aY, _T("default")) ? ATOI(aY) : rect.top // Y-position , *aWidth && _tcsicmp(aWidth, _T("default")) ? ATOI(aWidth) : rect.right - rect.left , *aHeight && _tcsicmp(aHeight, _T("default")) ? ATOI(aHeight) : rect.bottom - rect.top , TRUE); // Do repaint. DoWinDelay; return OK; } ResultType Line::ControlSend(LPTSTR aControl, LPTSTR aKeysToSend, LPTSTR aTitle, LPTSTR aText , LPTSTR aExcludeTitle, LPTSTR aExcludeText, bool aSendRaw) { HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) goto error; HWND control_window = _tcsicmp(aControl, _T("ahk_parent")) ? ControlExist(target_window, aControl) // This can return target_window itself for cases such as ahk_id %ControlHWND%. : target_window; if (!control_window) goto error; SendKeys(aKeysToSend, aSendRaw, SM_EVENT, control_window); // But don't do WinDelay because KeyDelay should have been in effect for the above. return g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Indicate success. error: return SetErrorLevelOrThrow(); } ResultType Line::ControlClick(vk_type aVK, int aClickCount, LPTSTR aOptions, LPTSTR aControl , LPTSTR aTitle, LPTSTR aText, LPTSTR aExcludeTitle, LPTSTR aExcludeText) { HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) goto error; // 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 (LPTSTR cp = aOptions; *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; } } // 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. HWND control_window = position_mode ? NULL : ControlExist(target_window, aControl); // This can return target_window itself for cases such as ahk_id %ControlHWND%. if (!control_window) // 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}; // Parse the X an Y coordinates in a strict way to reduce ambiguity with control names and also // to keep the code simple. LPTSTR cp = omit_leading_whitespace(aControl); if (ctoupper(*cp) != 'X') goto error;
tinku99/ahkdll
179cea5a711a0cf3681c042be0891ceab8393f8c
SendMode default to SendThenPlay
diff --git a/source/cpp.hint b/source/cpp.hint new file mode 100644 index 0000000..453bbab --- /dev/null +++ b/source/cpp.hint @@ -0,0 +1 @@ +#define BIF_DECL(name) BIF_ResultType name(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) \ No newline at end of file diff --git a/source/defines.h b/source/defines.h index 58d92e3..1e48137 100644 --- a/source/defines.h +++ b/source/defines.h @@ -240,602 +240,602 @@ struct ExprTokenType // Something in the compiler hates the name TokenType, so }; union // Due to the outermost union, this doesn't increase the total size of the struct on x86 builds (but it does on x64). It's used by SYM_FUNC (helps built-in functions), SYM_DYNAMIC, SYM_OPERAND, and perhaps other misc. purposes. { LPTSTR buf; size_t marker_length; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; }; }; // Note that marker's str-length should not be stored in this struct, even though it might be readily // available in places and thus help performance. This is because if it were stored and the marker // or SYM_VAR's var pointed to a location that was changed as a side effect of an expression's // call to a script function, the length would then be invalid. SymbolType symbol; // Short-circuit benchmark is currently much faster with this and the next beneath the union, perhaps due to CPU optimizations for 8-byte alignment. union { ExprTokenType *circuit_token; // Facilitates short-circuit boolean evaluation. LPTSTR mem_to_free; // Used only with aResultToken. TODO: Move into separate ResultTokenType struct. }; // The above two probably need to be adjacent to each other to conserve memory due to 8-byte alignment, // which is the default alignment (for performance reasons) in any struct that contains 8-byte members // such as double and __int64. }; #define MAX_TOKENS 512 // Max number of operators/operands. Seems enough to handle anything realistic, while conserving call-stack space. #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. // 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_ASSIGN, ACT_ASSIGNEXPR, ACT_EXPRESSION, ACT_ADD, ACT_SUB, ACT_MULT, ACT_DIV , ACT_ASSIGN_FIRST = ACT_ASSIGN, ACT_ASSIGN_LAST = ACT_DIV , ACT_REPEAT // Never parsed directly, only provided as a translation target for the old command (see other notes). , ACT_ELSE // Parsed at a lower level than most commands to support same-line ELSE-actions (e.g. "else if"). , ACT_IFIN, ACT_IFNOTIN, ACT_IFCONTAINS, ACT_IFNOTCONTAINS, ACT_IFIS, ACT_IFISNOT , ACT_IFBETWEEN, ACT_IFNOTBETWEEN , ACT_IFEXPR // i.e. if (expr) // *** *** *** KEEP ALL OLD-STYLE/AUTOIT V2 IFs AFTER THIS (v1.0.20 bug fix). *** *** *** , ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // ACT_IS_IF_OLD() relies upon ACT_IFEQUAL through ACT_IFLESSOREQUAL being adjacent to one another // and it relies upon the fact that ACT_IFEQUAL is first in the series and ACT_IFLESSOREQUAL last. , ACT_IFEQUAL = ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION, ACT_IFNOTEQUAL, ACT_IFGREATER, ACT_IFGREATEROREQUAL , ACT_IFLESS, ACT_IFLESSOREQUAL , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes. , ACT_IFWINEXIST = ACT_FIRST_COMMAND , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE , ACT_IFINSTRING, ACT_IFNOTINSTRING , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX // Keep this range updated with any new IFs that are added. , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE , ACT_GETKEYSTATE , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS , ACT_STATUSBARGETTEXT , ACT_STATUSBARWAIT , ACT_CLIPWAIT, ACT_KEYWAIT , ACT_SLEEP, ACT_RANDOM , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_CONTINUE // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_TRY, ACT_CATCH, ACT_THROW , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE , ACT_WINHIDE, ACT_WINSHOW , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE // Keep rarely used actions near the bottom for parsing/performance reasons: , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME , ACT_FILEGETSIZE, ACT_FILEGETVERSION , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_OUTPUTDEBUG , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME , ACT_SUSPEND, ACT_PAUSE , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET , ACT_EXITAPP , ACT_SHUTDOWN , ACT_FILEENCODING // Make these the last ones before the count so they will be less often processed. This helps // performance because this one doesn't actually have a keyword so will never result // in a match anyway. UPDATE: No longer used because Run/RunWait is now required, which greatly // improves syntax checking during load: //, ACT_EXEC // It's safer to use g_ActionCount, which is calculated immediately after the array is declared // and initialized, at which time we know its true size. However, the following lets us detect // when the size of the array doesn't match the enum (in debug mode): #ifdef _DEBUG , ACT_COUNT #endif }; enum enum_act_old { OLD_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order: , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL , OLD_LEFTCLICK, OLD_RIGHTCLICK, OLD_LEFTCLICKDRAG, OLD_RIGHTCLICKDRAG , OLD_HIDEAUTOITWIN, OLD_REPEAT, OLD_ENDREPEAT , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS }; // It seems best not to include ACT_SUSPEND in the below, since the user may have marked // a large number of subroutines as "Suspend, Permit". Even PAUSE is iffy, since the user // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey // was 1 (the default). #ifndef MINIDLL #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \ || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS) #else #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_RELOAD) #endif #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance. #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF) #define ACT_IS_IF_OR_ELSE_OR_LOOP(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ActionType == ACT_LOOP || ActionType == ACT_WHILE || ActionType == ACT_FOR) #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \ && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL)) // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new") // can support parameters on the same line or on the next line. For example, both of the above are allowed: // IfMsgBox, No, Gosub, XXX // IfMsgBox, No // Gosub, XXX // 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 // 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. #ifndef MINIDLL #define MAX_INPUTBOXES 4 #define MAX_PROGRESS_WINDOWS 10 // Allow a lot for downloads and such. #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above. #define MAX_SPLASHIMAGE_WINDOWS 10 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above. #endif #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. #ifndef MINIDLL #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #endif #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. #ifndef MINIDLL #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #endif #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. #ifndef MINIDLL // 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 #endif #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 CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close() #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; // Just make them int's, rather than something smaller, because the collection // of actions will take up very little memory. Int's are probably faster // for the processor to access since they are the native word size, or something: // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform() // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for // non-AutoIt2 scripts, such as the extra ones in StringGetPos). // Also, changing these from ints to chars greatly reduces 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, MaxParamsAu2WithHighBit; // Array indicating which args must be purely numeric. The first arg is // number 1, the second 2, etc (i.e. it doesn't start at zero). The list // is ended with a zero, much like a string. The compiler will notify us // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased: #define MAX_NUMERIC_PARAMS 7 ActionTypeType NumericParams[MAX_NUMERIC_PARAMS]; }; #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}; #ifndef MINIDLL 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("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")} enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely). , GUI_EVENT_RCLK, GUI_EVENT_COLCLK , GUI_EVENT_FIRST_UNNAMED // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below. , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield). #endif typedef USHORT CoordModeType; // Bit-field offsets: #ifndef MINIDLL #define COORD_MODE_PIXEL 0 #endif #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #ifndef MINIDLL #define COORD_MODE_MENU 8 #endif #define COORD_MODE_WINDOW 0 #define COORD_MODE_CLIENT 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #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; } // Same reason as above struct. It's best to keep this struct as small as possible // because it's used as a local (stack) var by at least one recursive function: // Each instance of this struct generally corresponds to a quasi-thread. The function that creates // a new thread typically saves the old thread's struct values on its stack so that they can later // be copied back into the g struct when the thread is resumed: class Func; // Forward declarations struct FuncAndToken { ExprTokenType mToken ; LPTSTR result_to_return_dll; Func * mFunc ; VARIANT variant_to_return_dll; }; class Label; // class Line; // struct RegItemStruct; // struct LoopReadFileStruct; // #ifndef MINIDLL class GuiType; // #endif struct global_struct { // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious). __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values. __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. WIN32_FIND_DATA *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. // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class // because they're more appropriate as thread-attributes rather than being global to the entire script. TitleMatchModes TitleMatchMode; int IntervalBeforeRest; int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible. int Priority; // This thread's priority relative to others. DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. #ifndef MINIDLL GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click. #endif EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard. #ifndef MINIDLL POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed. GuiType *GuiWindow; // The GUI window that launched this thread. GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..." GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid. GuiType *DialogOwner; // This thread's GUI owner, if any. GuiIndexType GuiControlIndex; // The GUI control index that launched this thread. #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL) #endif 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; // TCHAR FormatFloat[32]; Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine. Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. //HWND hWndToRestore; int MsgBoxResult; // Which button was pressed in the most recent MsgBox. HWND DialogHWND; // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: SendModes SendMode; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. DWORD ThreadStartTime; int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too). bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness. 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 AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. 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; CoordModeType CoordMode; // Bitwise collection of flags. UCHAR StringCaseSense; // On/Off/Locale bool StoreCapslockMode; bool AutoTrim; char FormatInt; SendLevelType SendLevel; bool MsgBoxTimedOut; // Doesn't require initialization. bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle". bool ListLinesIsEnabled; UINT Encoding; ExprTokenType* ThrownToken; Line* ExcptLine; bool InTryBlock; }; inline void global_maximize_interruptibility(global_struct &g) { g.AllowThreadToBeInterrupted = true; g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.ThreadIsCritical = false; g.AllowTimers = true; #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. } inline void global_clear_state(global_struct &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 ErrorLevel shouldn't). { g.CurrentFunc = NULL; g.CurrentFuncGosub = NULL; g.CurrentLabel = NULL; g.hWndLastUsed = NULL; //g.hWndToRestore = NULL; g.MsgBoxResult = 0; g.IsPaused = false; g.UninterruptedLineCount = 0; #ifndef MINIDLL g.DialogOwner = NULL; #endif g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true. #ifndef MINIDLL g.GuiDefaultWindow = NULL; #endif // Above line is done because allowing it to be permanently changed by the auto-exec section // seems like it would cause more confusion that it's worth. A change to the global default // or even an override/always-use-this-window-number mode can be added if there is ever a // demand for it. 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.InTryBlock = false; } inline void global_init(global_struct &g) // This isn't made a real constructor to avoid the overhead, since there are times when we // want to declare a local var of type global_struct without having it initialized. { // 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: global_clear_state(g); - g.SendMode = SM_EVENT; // v1.0.43: Default to SM_EVENT for backward compatibility. + g.SendMode = SM_INPUT_FALLBACK_TO_PLAY; // v1.1.7.3: Default to SM_INPUT_FALLBACK_TO_PLAY for best performance. g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3. 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. // Not sure what the optimal default is. 1 seems too low (scripts would be very slow by default): g.LinesPerCycle = -1; g.IntervalBeforeRest = 10; // sleep for 10ms every 10ms #define DEFAULT_PEEK_FREQUENCY 5 g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL. g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values. g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.AllowTimers = true; g.ThreadIsCritical = false; g.Priority = 0; g.LastError = 0; #ifndef MINIDLL g.GuiEvent = GUI_EVENT_NONE; #endif g.EventInfo = NO_EVENT_INFO; #ifndef MINIDLL g.GuiPoint.x = COORD_UNSPECIFIED; g.GuiPoint.y = COORD_UNSPECIFIED; // For these, indexes rather than pointers are stored because handles can become invalid during the // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself): g.GuiWindow = NULL; g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds. g.GuiDefaultWindow = NULL; #endif 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.StringCaseSense = SCS_INSENSITIVE; // AutoIt2 default, and it does seem best. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.AutoTrim = true; // AutoIt2's default, and overall the best default in most cases. _tcscpy(g.FormatFloat, _T("%0.6f")); g.FormatInt = 'D'; g.SendLevel = 0; g.ListLinesIsEnabled = true; g.Encoding = CP_ACP; // For FormatFloat: // I considered storing more than 6 digits to the right of the decimal point (which is the default // for most Unices and MSVC++ it seems). But going beyond that makes things a little weird for many // numbers, due to the inherent imprecision of floating point storage. For example, 83648.4 divided // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with // 20 digits. The extra zeros could be chopped off the end easily enough, but even so, going beyond // 6 digits seems to do more harm than good for the avg. user, overall. A default of 6 is used here // in case other/future compilers have a different default (for backward compatibility, we want // 6 to always be in effect as the default for future releases). } #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel. #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) // 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 diff --git a/source/globaldata.cpp b/source/globaldata.cpp index d4fa074..176579d 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,698 +1,698 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() HINSTANCE g_hInstance = NULL; // Set by WinMain(). DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. ATOM g_ClassRegistered = 0; ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; UINT g_DefaultScriptCodepage = UorA(CP_UTF8, CP_ACP); bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_AllowSameLineComments = true; bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. -SendModes g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. +SendModes g_HSSendMode = SM_INPUT_FALLBACK_TO_PLAY; // v1.1.7.03: New default for more reliable hotstrings and best performance. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} // This command is never directly parsed, but we need to have it here as a translation // target for the old "repeat" command. This is because that command treats a zero // first-param as an infinite loop. Since that param can be a dereferenced variable, // there's no way to reliably translate each REPEAT command into a LOOP command at // load-time. Thus, we support both types of loops as actual commands that are // handled separately at runtime. , {_T("Repeat"), 0, 1, 1, {1, 0}} // Iteration Count: was mandatory in AutoIt2 but doesn't seem necessary here. , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("Continue"), 0, 1, 1, NULL} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {_T("IniRead"), 2, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) , {_T("IniWrite"), 3, 4, 4, NULL} // Value, Filespec, Section, Key , {_T("IniDelete"), 2, 3, 3, NULL} // Filespec, Section, Key // These require so few parameters due to registry loops, which provide the missing parameter values // automatically. In addition, RegRead can't require more than 1 param since the 2nd param is // an option/obsolete parameter: , {_T("RegRead"), 1, 5, 5 H, NULL} // output var, (ValueType [optional]), RegKey, RegSubkey, ValueName , {_T("RegWrite"), 0, 5, 5, NULL} // ValueType, RegKey, RegSubKey, ValueName, Value (set to blank if omitted?) , {_T("RegDelete"), 0, 3, 3, NULL} // RegKey, RegSubKey, ValueName , {_T("OutputDebug"), 1, 1, 1, NULL} , {_T("SetKeyDelay"), 0, 3, 3, {1, 2, 0}} // Delay in ms (numeric, negative allowed), PressDuration [, Play] , {_T("SetMouseDelay"), 1, 2, 2, {1, 0}} // Delay in ms (numeric, negative allowed) [, Play] , {_T("SetWinDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetControlDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetBatchLines"), 1, 1, 1, NULL} // Can be non-numeric, such as 15ms, or a number (to indicate line count). , {_T("SetTitleMatchMode"), 1, 1, 1, NULL} // Allowed values: 1, 2, slow, fast , {_T("SetFormat"), 2, 2, 2, NULL} // Float|Integer, FormatString (for float) or H|D (for int) , {_T("FormatTime"), 1, 3, 3 H, NULL} // OutputVar, YYYYMMDDHH24MISS, Format (format is last to avoid having to escape commas in it). , {_T("Suspend"), 0, 1, 1, NULL} // On/Off/Toggle/Permit/Blank (blank is the same as toggle) , {_T("Pause"), 0, 2, 2, NULL} // On/Off/Toggle/Blank (blank is the same as toggle), AlwaysAffectUnderlying , {_T("AutoTrim"), 1, 1, 1, NULL} // On/Off , {_T("StringCaseSense"), 1, 1, 1, NULL} // On/Off/Locale , {_T("DetectHiddenWindows"), 1, 1, 1, NULL} // On/Off , {_T("DetectHiddenText"), 1, 1, 1, NULL} // On/Off , {_T("BlockInput"), 1, 1, 1, NULL} // On/Off , {_T("SetNumlockState"), 0, 1, 1, NULL} // On/Off/AlwaysOn/AlwaysOff or blank (unspecified) to return to normal. , {_T("SetScrollLockState"), 0, 1, 1, NULL} // same , {_T("SetCapslockState"), 0, 1, 1, NULL} // same , {_T("SetStoreCapslockMode"), 1, 1, 1, NULL} // On/Off , {_T("KeyHistory"), 0, 2, 2, NULL}, {_T("ListLines"), 0, 1, 1, NULL} , {_T("ListVars"), 0, 0, 0, NULL}, {_T("ListHotkeys"), 0, 0, 0, NULL} , {_T("Edit"), 0, 0, 0, NULL} , {_T("Reload"), 0, 0, 0, NULL} , {_T("Menu"), 2, 6, 6, NULL} // tray, add, name, label, options, future use , {_T("Gui"), 1, 4, 4, NULL} // Cmd/Add, ControlType, Options, Text , {_T("GuiControl"), 0, 3, 3 H, NULL} // Sub-cmd (defaults to "contents"), ControlName/ID, Text , {_T("GuiControlGet"), 1, 4, 4, NULL} // OutputVar, Sub-cmd (defaults to "contents"), ControlName/ID (defaults to control assoc. with OutputVar), Text/FutureUse , {_T("ExitApp"), 0, 1, 1, {1, 0}} // Optional exit-code. v1.0.48.01: Allow an expression like ACT_EXIT does. , {_T("Shutdown"), 1, 1, 1, {1, 0}} // Seems best to make the first param (the flag/code) mandatory. , {_T("FileEncoding"), 0, 1, 1, NULL} }; // Below is the most maintainable way to determine the actual count? // Due to C++ lang. restrictions, can't easily make this a const because constants // automatically get static (internal) linkage, thus such a var could never be // used outside this module: int g_ActionCount = _countof(g_act); Action g_old_act[] = { {_T(""), 0, 0, 0, NULL} // OLD_INVALID. , {_T("SetEnv"), 1, 2, 2, NULL} , {_T("EnvAdd"), 2, 3, 3, {2, 0}}, {_T("EnvSub"), 1, 3, 3, {2, 0}} // EnvSub (but not Add) allow 2nd to be blank due to 3rd param. , {_T("EnvMult"), 2, 2, 2, {2, 0}}, {_T("EnvDiv"), 2, 2, 2, {2, 0}} , {_T("IfEqual"), 1, 2, 2, NULL}, {_T("IfNotEqual"), 1, 2, 2, NULL} , {_T("IfGreater"), 1, 2, 2, NULL}, {_T("IfGreaterOrEqual"), 1, 2, 2, NULL} , {_T("IfLess"), 1, 2, 2, NULL}, {_T("IfLessOrEqual"), 1, 2, 2, NULL} , {_T("LeftClick"), 2, 2, 2, {1, 2, 0}}, {_T("RightClick"), 2, 2, 2, {1, 2, 0}} , {_T("LeftClickDrag"), 4, 4, 4, {1, 2, 3, 4, 0}}, {_T("RightClickDrag"), 4, 4, 4, {1, 2, 3, 4, 0}} , {_T("HideAutoItWin"), 1, 1, 1, NULL} // Allow zero params, unlike AutoIt. These params should match those for REPEAT in the above array: , {_T("Repeat"), 0, 1, 1, {1, 0}}, {_T("EndRepeat"), 0, 0, 0, NULL} , {_T("WinGetActiveTitle"), 1, 1, 1, NULL} // <Title Var> , {_T("WinGetActiveStats"), 5, 5, 5, NULL} // <Title Var>, <Width Var>, <Height Var>, <Xpos Var>, <Ypos Var> }; int g_OldActionCount = _countof(g_old_act); key_to_vk_type g_key_to_vk[] = { {_T("Numpad0"), VK_NUMPAD0} , {_T("Numpad1"), VK_NUMPAD1} , {_T("Numpad2"), VK_NUMPAD2} , {_T("Numpad3"), VK_NUMPAD3} , {_T("Numpad4"), VK_NUMPAD4} , {_T("Numpad5"), VK_NUMPAD5} , {_T("Numpad6"), VK_NUMPAD6} , {_T("Numpad7"), VK_NUMPAD7} , {_T("Numpad8"), VK_NUMPAD8} , {_T("Numpad9"), VK_NUMPAD9} , {_T("NumpadMult"), VK_MULTIPLY} , {_T("NumpadDiv"), VK_DIVIDE} , {_T("NumpadAdd"), VK_ADD} , {_T("NumpadSub"), VK_SUBTRACT} // , {_T("NumpadEnter"), VK_RETURN} // Must do this one via scan code, see below for explanation. , {_T("NumpadDot"), VK_DECIMAL} , {_T("Numlock"), VK_NUMLOCK} , {_T("ScrollLock"), VK_SCROLL} , {_T("CapsLock"), VK_CAPITAL} , {_T("Escape"), VK_ESCAPE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Esc"), VK_ESCAPE} , {_T("Tab"), VK_TAB} , {_T("Space"), VK_SPACE} , {_T("Backspace"), VK_BACK} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("BS"), VK_BACK} // These keys each have a counterpart on the number pad with the same VK. Use the VK for these, // since they are probably more likely to be assigned to hotkeys (thus minimizing the use of the // keyboard hook, and use the scan code (SC) for their counterparts. UPDATE: To support handling // these keys with the hook (i.e. the sc_takes_precedence flag in the hook), do them by scan code // instead. This allows Numpad keys such as Numpad7 to be differentiated from NumpadHome, which // would otherwise be impossible since both of them share the same scan code (i.e. if the // sc_takes_precedence flag is set for the scan code of NumpadHome, that will effectively prevent // the hook from telling the difference between it and Numpad7 since the hook is currently set // to handle an incoming key by either vk or sc, but not both. // Even though ENTER is probably less likely to be assigned than NumpadEnter, must have ENTER as // the primary vk because otherwise, if the user configures only naked-NumPadEnter to do something, // RegisterHotkey() would register that vk and ENTER would also be configured to do the same thing. , {_T("Enter"), VK_RETURN} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Return"), VK_RETURN} , {_T("NumpadDel"), VK_DELETE} , {_T("NumpadIns"), VK_INSERT} , {_T("NumpadClear"), VK_CLEAR} // same physical key as Numpad5 on most keyboards? , {_T("NumpadUp"), VK_UP} , {_T("NumpadDown"), VK_DOWN} , {_T("NumpadLeft"), VK_LEFT} , {_T("NumpadRight"), VK_RIGHT} , {_T("NumpadHome"), VK_HOME} , {_T("NumpadEnd"), VK_END} , {_T("NumpadPgUp"), VK_PRIOR} , {_T("NumpadPgDn"), VK_NEXT} , {_T("PrintScreen"), VK_SNAPSHOT} , {_T("CtrlBreak"), VK_CANCEL} // Might want to verify this, and whether it has any peculiarities. , {_T("Pause"), VK_PAUSE} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Break"), VK_PAUSE} // Not really meaningful, but kept for as a synonym of Pause for backward compatibility. See CtrlBreak. , {_T("Help"), VK_HELP} // VK_HELP is probably not the extended HELP key. Not sure what this one is. , {_T("Sleep"), VK_SLEEP} , {_T("AppsKey"), VK_APPS} // UPDATE: For the NT/2k/XP version, now doing these by VK since it's likely to be // more compatible with non-standard or non-English keyboards: , {_T("LControl"), VK_LCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("RControl"), VK_RCONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("LCtrl"), VK_LCONTROL} // Abbreviated versions of the above. , {_T("RCtrl"), VK_RCONTROL} // , {_T("LShift"), VK_LSHIFT} , {_T("RShift"), VK_RSHIFT} , {_T("LAlt"), VK_LMENU} , {_T("RAlt"), VK_RMENU} // These two are always left/right centric and I think their vk's are always supported by the various // Windows API calls, unlike VK_RSHIFT, etc. (which are seldom supported): , {_T("LWin"), VK_LWIN} , {_T("RWin"), VK_RWIN} // The left/right versions of these are handled elsewhere since their virtual keys aren't fully API-supported: , {_T("Control"), VK_CONTROL} // So that VKtoKeyName() delivers consistent results, always have the preferred name first. , {_T("Ctrl"), VK_CONTROL} // An alternate for convenience. , {_T("Alt"), VK_MENU} , {_T("Shift"), VK_SHIFT} /* These were used to confirm the fact that you can't use RegisterHotkey() on VK_LSHIFT, even if the shift modifier is specified along with it: , {_T("LShift"), VK_LSHIFT} , {_T("RShift"), VK_RSHIFT} */ , {_T("F1"), VK_F1} diff --git a/source/util.cpp b/source/util.cpp index 956057f..1c4c311 100644 --- a/source/util.cpp +++ b/source/util.cpp @@ -1207,1076 +1207,1088 @@ size_t PredictReplacementSize(ptrdiff_t aLengthDelta, int aReplacementCount, int + total_delta; // This is additional_replacements_expected times the expected delta (the length of each replacement minus what it replaces) [can be negative]. if (subsequent_length < 0) // Must not go below zero because that would cause the next line to subsequent_length = 0; // create an increase that's too small to handle the current replacement. // Return the sum of the following: // 1) subsequent_length: The predicted length needed for the remainder of the operation. // 2) aCurrentLength: The amount we need now, which includes room for the replacement the caller is about to do. // Note that aCurrentLength can be 0 (such as for an empty string replacement). return subsequent_length + aCurrentLength + 1; // Caller relies on +1 for the terminator. } LPTSTR TranslateLFtoCRLF(LPTSTR aString) // Can't use StrReplace() for this because any CRLFs originally present in aString are not changed (i.e. they // don't become CRCRLF) [there may be other reasons]. // Translates any naked LFs in aString to CRLF. If there are none, the original string is returned. // Otherwise, the translated version is copied into a malloc'd buffer, which the caller must free // when it's done with it). { UINT naked_LF_count = 0; size_t length = 0; LPTSTR cp; for (cp = aString; *cp; ++cp) { ++length; if (*cp == '\n' && (cp == aString || cp[-1] != '\r')) // Relies on short-circuit boolean order. ++naked_LF_count; } if (!naked_LF_count) return aString; // The original string is returned, which the caller must check for (vs. new string). // Allocate the new memory that will become the caller's responsibility: LPTSTR buf = (LPTSTR)tmalloc(length + naked_LF_count + 1); // +1 for zero terminator. if (!buf) return NULL; // Now perform the translation. LPTSTR dp = buf; // Destination. for (cp = aString; *cp; ++cp) { if (*cp == '\n' && (cp == aString || cp[-1] != '\r')) // Relies on short-circuit boolean order. *dp++ = '\r'; // Insert an extra CR here, then insert the '\n' normally below. *dp++ = *cp; } *dp = '\0'; // Final terminator. return buf; // Caller must free it when it's done with it. } bool DoesFilePatternExist(LPTSTR aFilePattern, DWORD *aFileAttr) // Returns true if the file/folder exists or false otherwise. // If non-NULL, aFileAttr's DWORD is set to the attributes of the file/folder if a match is found. // If there is no match, its contents are undefined. { if (!aFilePattern || !*aFilePattern) return false; // Fix for v1.0.35.12: Don't consider the question mark in "\\?\Volume{GUID}\" to be a wildcard. // Such volume names are obtained from GetVolumeNameForVolumeMountPoint() and perhaps other functions. // However, testing shows that wildcards beyond that first one should be seen as real wildcards // because the wildcard match-method below does work for such volume names. LPTSTR cp = _tcsncmp(aFilePattern, _T("\\\\?\\"), 4) ? aFilePattern : aFilePattern + 4; if (StrChrAny(cp, _T("?*"))) { WIN32_FIND_DATA wfd; HANDLE hFile = FindFirstFile(aFilePattern, &wfd); if (hFile == INVALID_HANDLE_VALUE) return false; FindClose(hFile); if (aFileAttr) *aFileAttr = wfd.dwFileAttributes; return true; } else { DWORD attr = GetFileAttributes(aFilePattern); if (aFileAttr) *aFileAttr = attr; return attr != 0xFFFFFFFF; } } #ifdef _DEBUG ResultType FileAppend(LPTSTR aFilespec, LPTSTR aLine, bool aAppendNewline) { if (!aFilespec || !aLine) return FAIL; if (!*aFilespec) return FAIL; FILE *fp = _tfopen(aFilespec, _T("a")); if (fp == NULL) return FAIL; _fputts(aLine, fp); if (aAppendNewline) _puttc('\n', fp); fclose(fp); return OK; } #endif LPTSTR ConvertFilespecToCorrectCase(LPTSTR aFullFileSpec) // aFullFileSpec must be a modifiable string since it will be converted to proper case. // Also, it should be at least MAX_PATH is size because if it contains any short (8.3) // components, they will be converted into their long names. // Returns aFullFileSpec, the contents of which have been converted to the case used by the // file system. Note: The trick of changing the current directory to be that of // aFullFileSpec and then calling GetFullPathName() doesn't always work. So perhaps the // only easy way is to call FindFirstFile() on each directory that composes aFullFileSpec, // which is what is done here. I think there's another way involving some PIDL Explorer // function, but that might not support UNCs correctly. { if (!aFullFileSpec || !*aFullFileSpec) return aFullFileSpec; size_t length = _tcslen(aFullFileSpec); if (length < 2 || length >= MAX_PATH) return aFullFileSpec; // Start with something easy, the drive letter: if (aFullFileSpec[1] == ':') aFullFileSpec[0] = ctoupper(aFullFileSpec[0]); // else it might be a UNC that has no drive letter. TCHAR built_filespec[MAX_PATH], *dir_start, *dir_end; if (dir_start = _tcschr(aFullFileSpec, ':')) // MSDN: "To examine any directory other than a root directory, use an appropriate // path to that directory, with no trailing backslash. For example, an argument of // "C:\windows" will return information about the directory "C:\windows", not about // any directory or file in "C:\windows". An attempt to open a search with a trailing // backslash will always fail." dir_start += 2; // Skip over the first backslash that goes with the drive letter. else // it's probably a UNC { if (_tcsncmp(aFullFileSpec, _T("\\\\"), 2)) // It doesn't appear to be a UNC either, so not sure how to deal with it. return aFullFileSpec; // I think MS says you can't use FindFirstFile() directly on a share name, so we // want to omit both that and the server name from consideration (i.e. we don't attempt // to find their proper case). MSDN: "Similarly, on network shares, you can use an // lpFileName of the form "\\server\service\*" but you cannot use an lpFileName that // points to the share itself, such as "\\server\service". dir_start = aFullFileSpec + 2; LPTSTR end_of_server_name = _tcschr(dir_start, '\\'); if (end_of_server_name) { dir_start = end_of_server_name + 1; LPTSTR end_of_share_name = _tcschr(dir_start, '\\'); if (end_of_share_name) dir_start = end_of_share_name + 1; } } // Init the new string (the filespec we're building), e.g. copy just the "c:\\" part. tcslcpy(built_filespec, aFullFileSpec, dir_start - aFullFileSpec + 1); WIN32_FIND_DATA found_file; HANDLE file_search; for (dir_end = dir_start; dir_end = _tcschr(dir_end, '\\'); ++dir_end) { *dir_end = '\0'; // Temporarily terminate. file_search = FindFirstFile(aFullFileSpec, &found_file); *dir_end = '\\'; // Restore it before we do anything else. if (file_search == INVALID_HANDLE_VALUE) return aFullFileSpec; FindClose(file_search); // Append the case-corrected version of this directory name: sntprintfcat(built_filespec, _countof(built_filespec), _T("%s\\"), found_file.cFileName); } // Now do the filename itself: if ( (file_search = FindFirstFile(aFullFileSpec, &found_file)) == INVALID_HANDLE_VALUE ) return aFullFileSpec; FindClose(file_search); sntprintfcat(built_filespec, _countof(built_filespec), _T("%s"), found_file.cFileName); // It might be possible for the new one to be longer than the old, e.g. if some 8.3 short // names were converted to long names by the process. Thus, the caller should ensure that // aFullFileSpec is large enough: _tcscpy(aFullFileSpec, built_filespec); return aFullFileSpec; } LPTSTR FileAttribToStr(LPTSTR aBuf, DWORD aAttr) // Caller must ensure that aAttr is valid (i.e. that it's not 0xFFFFFFFF). { if (!aBuf) return aBuf; int length = 0; if (aAttr & FILE_ATTRIBUTE_READONLY) aBuf[length++] = 'R'; if (aAttr & FILE_ATTRIBUTE_ARCHIVE) aBuf[length++] = 'A'; if (aAttr & FILE_ATTRIBUTE_SYSTEM) aBuf[length++] = 'S'; if (aAttr & FILE_ATTRIBUTE_HIDDEN) aBuf[length++] = 'H'; if (aAttr & FILE_ATTRIBUTE_NORMAL) aBuf[length++] = 'N'; if (aAttr & FILE_ATTRIBUTE_DIRECTORY) aBuf[length++] = 'D'; if (aAttr & FILE_ATTRIBUTE_OFFLINE) aBuf[length++] = 'O'; if (aAttr & FILE_ATTRIBUTE_COMPRESSED) aBuf[length++] = 'C'; if (aAttr & FILE_ATTRIBUTE_TEMPORARY) aBuf[length++] = 'T'; aBuf[length] = '\0'; // Perform the final termination. return aBuf; } unsigned __int64 GetFileSize64(HANDLE aFileHandle) // Returns ULLONG_MAX on failure. Otherwise, it returns the actual file size. { ULARGE_INTEGER ui = {0}; ui.LowPart = GetFileSize(aFileHandle, &ui.HighPart); if (ui.LowPart == MAXDWORD && GetLastError() != NO_ERROR) return ULLONG_MAX; return (unsigned __int64)ui.QuadPart; } LPTSTR GetLastErrorText(LPTSTR aBuf, int aBufSize, bool aUpdateLastError) // aBufSize is an int to preserve any negative values the caller might pass in. { if (aBufSize < 1) return aBuf; if (aBufSize == 1) { *aBuf = '\0'; return aBuf; } DWORD last_error = GetLastError(); if (aUpdateLastError) g->LastError = last_error; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, last_error, 0, aBuf, (DWORD)aBufSize - 1, NULL); return aBuf; } void AssignColor(LPTSTR aColorName, COLORREF &aColor, HBRUSH &aBrush) // Assign the color indicated in aColorName (either a name or a hex RGB value) to both // aColor and aBrush, deleting any prior handle in aBrush first. If the color cannot // be determined, it will always be set to CLR_DEFAULT (and aBrush set to NULL to match). // It will never be set to CLR_NONE. { COLORREF color; if (!*aColorName) color = CLR_DEFAULT; else { color = ColorNameToBGR(aColorName); if (color == CLR_NONE) // A matching color name was not found, so assume it's a hex color value. // It seems strtol() automatically handles the optional leading "0x" if present: color = rgb_to_bgr(_tcstol(aColorName, NULL, 16)); // if aColorName does not contain something hex-numeric, black (0x00) will be assumed, // which seems okay given how rare such a problem would be. } if (color != aColor) // It's not already the right color. { aColor = color; // Set default. v1.0.44.09: Added this line to fix the inability to change to a previously selected color after having changed to the default color. if (aBrush) // Free the resources of the old brush. DeleteObject(aBrush); if (color == CLR_DEFAULT) // Caller doesn't need brush for CLR_DEFAULT, assuming that's even possible. aBrush = NULL; else if ( !(aBrush = CreateSolidBrush(color)) ) // Failure should be very rare. aColor = CLR_DEFAULT; // A NULL HBRUSH should always corresponds to CLR_DEFAULT. } } COLORREF ColorNameToBGR(LPTSTR aColorName) // These are the main HTML color names. Returns CLR_NONE if a matching HTML color name can't be found. // Returns CLR_DEFAULT only if aColorName is the word Default. { if (!aColorName || !*aColorName) return CLR_NONE; if (!_tcsicmp(aColorName, _T("Black"))) return 0x000000; // These colors are all in BGR format, not RGB. if (!_tcsicmp(aColorName, _T("Silver"))) return 0xC0C0C0; if (!_tcsicmp(aColorName, _T("Gray"))) return 0x808080; if (!_tcsicmp(aColorName, _T("White"))) return 0xFFFFFF; if (!_tcsicmp(aColorName, _T("Maroon"))) return 0x000080; if (!_tcsicmp(aColorName, _T("Red"))) return 0x0000FF; if (!_tcsicmp(aColorName, _T("Purple"))) return 0x800080; if (!_tcsicmp(aColorName, _T("Fuchsia")))return 0xFF00FF; if (!_tcsicmp(aColorName, _T("Green"))) return 0x008000; if (!_tcsicmp(aColorName, _T("Lime"))) return 0x00FF00; if (!_tcsicmp(aColorName, _T("Olive"))) return 0x008080; if (!_tcsicmp(aColorName, _T("Yellow"))) return 0x00FFFF; if (!_tcsicmp(aColorName, _T("Navy"))) return 0x800000; if (!_tcsicmp(aColorName, _T("Blue"))) return 0xFF0000; if (!_tcsicmp(aColorName, _T("Teal"))) return 0x808000; if (!_tcsicmp(aColorName, _T("Aqua"))) return 0xFFFF00; if (!_tcsicmp(aColorName, _T("Default")))return CLR_DEFAULT; return CLR_NONE; } POINT CenterWindow(int aWidth, int aHeight) // Given a the window's width and height, calculates where to position its upper-left corner // so that it is centered EVEN IF the task bar is on the left side or top side of the window. // This does not currently handle multi-monitor systems explicitly, since those calculations // require API functions that don't exist in Win95/NT (and thus would have to be loaded // dynamically to allow the program to launch). Therefore, windows will likely wind up // being centered across the total dimensions of all monitors, which usually results in // half being on one monitor and half in the other. This doesn't seem too terrible and // might even be what the user wants in some cases (i.e. for really big windows). { RECT rect; SystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0); // Get desktop rect excluding task bar. // Note that rect.left will NOT be zero if the taskbar is on docked on the left. // Similarly, rect.top will NOT be zero if the taskbar is on docked at the top of the screen. POINT pt; pt.x = rect.left + (((rect.right - rect.left) - aWidth) / 2); pt.y = rect.top + (((rect.bottom - rect.top) - aHeight) / 2); return pt; } bool FontExist(HDC aHdc, LPCTSTR aTypeface) { LOGFONT lf; lf.lfCharSet = DEFAULT_CHARSET; // Enumerate all char sets. lf.lfPitchAndFamily = 0; // Must be zero. tcslcpy(lf.lfFaceName, aTypeface, LF_FACESIZE); bool font_exists = false; EnumFontFamiliesEx(aHdc, &lf, (FONTENUMPROC)FontEnumProc, (LPARAM)&font_exists, 0); return font_exists; } int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam) { *(bool *)lParam = true; // Indicate to the caller that the font exists. return 0; // Stop the enumeration after the first, since even one match means the font exists. } void ScreenToWindow(POINT &aPoint, HWND aHwnd) // Convert screen coordinates to window coordinates (i.e. relative to the window's upper-left corner). { RECT rect; GetWindowRect(aHwnd, &rect); aPoint.x -= rect.left; aPoint.y -= rect.top; } void CoordToScreen(int &aX, int &aY, int aWhichMode) // aX and aY are interpreted according to the current coord mode. If necessary, they are converted to // screen coordinates based on the position of the active window's upper-left corner (or its client area). { int coord_mode = ((g->CoordMode >> aWhichMode) & COORD_MODE_MASK); if (coord_mode == COORD_MODE_SCREEN) return; HWND active_window = GetForegroundWindow(); if (active_window && !IsIconic(active_window)) { if (coord_mode == COORD_MODE_WINDOW) { RECT rect; if (GetWindowRect(active_window, &rect)) { aX += rect.left; aY += rect.top; } } else // (coord_mode == COORD_MODE_CLIENT) { POINT pt = {0}; if (ClientToScreen(active_window, &pt)) { aX += pt.x; aY += pt.y; } } } //else no active window per se, so don't convert the coordinates. Leave them as-is as desired // by the caller. More details: // Revert to screen coordinates if the foreground window is minimized. Although it might be // impossible for a visible window to be both foreground and minimized, it seems that hidden // windows -- such as the script's own main window when activated for the purpose of showing // a popup menu -- can be foreground while simultaneously being minimized. This fixes an // issue where the mouse will move to the upper-left corner of the screen rather than the // intended coordinates (v1.0.17). } void CoordToScreen(POINT &aPoint, int aWhichMode) // For convenience. See function above for comments. { CoordToScreen((int &)aPoint.x, (int &)aPoint.y, aWhichMode); } void GetVirtualDesktopRect(RECT &aRect) { aRect.right = GetSystemMetrics(SM_CXVIRTUALSCREEN); if (aRect.right) // A non-zero value indicates the OS supports multiple monitors or at least SM_CXVIRTUALSCREEN. { aRect.left = GetSystemMetrics(SM_XVIRTUALSCREEN); // Might be negative or greater than zero. aRect.right += aRect.left; aRect.top = GetSystemMetrics(SM_YVIRTUALSCREEN); // Might be negative or greater than zero. aRect.bottom = aRect.top + GetSystemMetrics(SM_CYVIRTUALSCREEN); } else // Win95/NT do not support SM_CXVIRTUALSCREEN and such, so zero was returned. GetWindowRect(GetDesktopWindow(), &aRect); } DWORD GetEnvVarReliable(LPCTSTR aEnvVarName, LPTSTR aBuf) // Returns the length of what has been copied into aBuf. // Caller has ensured that aBuf is large enough (though anything >=32767 is always large enough). // This function was added in v1.0.46.08 to fix a long-standing bug that was more fully revealed // by 1.0.46.07's reduction of DEREF_BUF_EXPAND_INCREMENT from 32 to 16K (which allowed the Win9x // version of GetEnvironmentVariable() to detect that we were lying about the buffer being 32767 // in size). The reason for lying is that we don't know exactly how big the buffer is, but we do // know it's large enough. So we just pass 32767 in an attempt to make it always succeed // (mostly because GetEnvironmentVariable() is such a slow call, so it's best to avoid calling it // a second time just to get the length). // UPDATE: This is now called for all versions of Windows to avoid any chance of crashing or misbehavior, // which tends to happen whenever lying to the API (even if it's for a good cause). See similar problems // at ReadRegString(). See other comments below. { // Windows 9x is apparently capable of detecting a lie about the buffer size. // For example, if the memory capacity is only 16K but we pass 32767, it sometimes/always detects that // and returns 0, even if the string being retrieved is short enough (which it is because the caller // already verified it). To work around this, give it a genuinely large buffer with an accurate size, // then copy the result out into the caller's variable. This is almost certainly much faster than // doing a second call to GetEnvironmentVariable() to get the length because GetEnv() is known to be a // very slow call. // // Don't use a size greater than 32767 because that will cause it to fail on Win95 (tested by Robert Yalkin). // According to MSDN, 32767 is exactly large enough to handle the largest variable plus its zero terminator. TCHAR buf[32767]; DWORD length = GetEnvironmentVariable(aEnvVarName, buf, _countof(buf)); // GetEnvironmentVariable() could be called twice, the first time to get the actual size. But that would // probably perform worse since GetEnvironmentVariable() is a very slow function. In addition, it would // add code complexity, so it seems best to fetch it into a large buffer then just copy it to dest-var. if (length) // Probably always true under the conditions in effect for our callers. tmemcpy(aBuf, buf, length + 1); // memcpy() usually benches a little faster than strcpy(). else // Failure. The buffer's contents might be undefined in this case. *aBuf = '\0'; // Caller's buf should always have room for an empty string. So make it empty for maintainability, even if not strictly required by caller. return length; } DWORD ReadRegString(HKEY aRootKey, LPTSTR aSubkey, LPTSTR aValueName, LPTSTR aBuf, DWORD aBufSize) // Returns the length of the string (0 if empty). // Caller must ensure that size of aBuf is REALLY aBufSize (even when it knows aBufSize is more than // it needs) because the API apparently reads/writes parts of the buffer beyond the string it writes! // Caller must ensure that aBuf isn't NULL because it doesn't seem worth having a "give me the size only" mode. // This is because the API might return a size that omits the zero terminator, and the only way to find out for // sure is probably to actually fetch the data and check if the terminator is present. { HKEY hkey; if (RegOpenKeyEx(aRootKey, aSubkey, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) { *aBuf = '\0'; return 0; } DWORD buf_size = aBufSize * sizeof(TCHAR); // Caller's value might be a constant memory area, so need a modifiable copy. LONG result = RegQueryValueEx(hkey, aValueName, NULL, NULL, (LPBYTE)aBuf, &buf_size); RegCloseKey(hkey); if (result != ERROR_SUCCESS || !buf_size) // Relies on short-circuit boolean order. { *aBuf = '\0'; // MSDN says the contents of the buffer is undefined after the call in some cases, so reset it. return 0; } buf_size /= sizeof(TCHAR); // RegQueryValueEx returns size in bytes. // Otherwise success and non-empty result. This also means that buf_size is accurate and <= to what we sent in. // Fix for v1.0.47: ENSURE PROPER STRING TERMINATION. This is suspected to be a source of crashing. // MSDN: "If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, the string may not have been // stored with the proper null-terminating characters. Therefore, even if the function returns // ERROR_SUCCESS, the application should ensure that the string is properly terminated before using // it; otherwise, it may overwrite a buffer. (Note that REG_MULTI_SZ strings should have two // null-terminating characters.)" // MSDN: "If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, this size includes any // terminating null character or characters." --buf_size; // Convert to the index of the last character written. This is safe because above already checked that buf_size>0. if (aBuf[buf_size] == '\0') // It wrote at least one zero terminator (it might write more than one for Unicode, or if it's simply stored with more than one in the registry). { while (buf_size && !aBuf[buf_size - 1]) // Scan leftward in case more than one consecutive terminator. --buf_size; return buf_size; // There's a tiny chance that this could the wrong length, namely when the string contains binary zero(s) to the left of non-zero characters. But that seems too rare to be worth calling strlen() for. } // Otherwise, it didn't write a terminator, so provide one. ++buf_size; // To reflect the fact that we're about to write an extra char. if (buf_size >= aBufSize) // There's no room for a terminator without truncating the data (very rare). Seems best to indicate failure. { *aBuf = '\0'; return 0; } // Otherwise, there's room for the terminator. aBuf[buf_size] = '\0'; return buf_size; // There's a tiny chance that this could the wrong length, namely when the string contains binary zero(s) to the left of non-zero characters. But that seems too rare to be worth calling strlen() for. } -LPVOID AllocInterProcMem(HANDLE &aHandle, DWORD aSize, HWND aHwnd) -// aHandle is an output parameter that holds the mapping for Win9x and the process handle for NT. -// Returns NULL on failure (in which case caller should ignore the value of aHandle). +BOOL IsProcess64Bit(HANDLE aHandle) { - // ALLOCATE APPROPRIATE TYPE OF MEMORY (depending on OS type) - LPVOID mem; - if (g_os.IsWin9x()) // Use file-mapping method. - { - if ( !(aHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, aSize, NULL)) ) - return NULL; - mem = MapViewOfFile(aHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0); - } - else // NT/2k/XP/2003 or later. Use the VirtualAllocEx() so that caller can use Read/WriteProcessMemory(). + BOOL is32on64; +#ifdef _WIN64 + // No need to load the function dynamically in this case since it should exist on all OSes + // which are able to load 64-bit executables (such as ours): + if (IsWow64Process(aHandle, &is32on64)) + return !is32on64; // 64-bit if not running under WOW64. + // Since above didn't return, an error occurred. MSDN isn't clear about what conditions can + // cause this, so for simplicity just assume the target process is 64-bit (like this one). + return TRUE; +#else + // Load function dynamically to allow the program to launch on Win2k/XPSP1: + typedef BOOL (WINAPI *MyIsWow64ProcessType)(HANDLE, PBOOL); + static MyIsWow64ProcessType MyIsWow64Process = (MyIsWow64ProcessType)GetProcAddress(GetModuleHandle(_T("kernel32")) + , "IsWow64Process"); + if (MyIsWow64Process && MyIsWow64Process(GetCurrentProcess(), &is32on64)) { - DWORD pid; - GetWindowThreadProcessId(aHwnd, &pid); - // Even if the PID is our own, open the process anyway to simplify the code. After all, it would be - // pretty silly for a script to access its own ListViews via this method. - if ( !(aHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, pid)) ) - return NULL; // Let ErrorLevel tell the story. - // Load function dynamically to allow program to launch on win9x: - typedef LPVOID (WINAPI *MyVirtualAllocExType)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD); - static MyVirtualAllocExType MyVirtualAllocEx = (MyVirtualAllocExType)GetProcAddress(GetModuleHandle(_T("kernel32")) - , "VirtualAllocEx"); - // Reason for using VirtualAllocEx(): When sending LVITEM structures to a control in a remote process, the - // structure and its pszText buffer must both be memory inside the remote process rather than in our own. - mem = MyVirtualAllocEx(aHandle, NULL, aSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (is32on64) + { + // We're running under WOW64. Since WOW64 only exists on 64-bit systems and on such systems + // 32-bit processes can run ONLY under WOW64, if the target process is also running under + // WOW64 it must be 32-bit; otherwise it must be 64-bit. + if (MyIsWow64Process(aHandle, &is32on64)) + return !is32on64; + } } + // Since above didn't return, one of the following is true: + // a) IsWow64Process doesn't exist, so the OS and all running processes must be 32-bit. + // b) IsWow64Process failed on the first or second call. MSDN isn't clear about what conditions + // can cause this, so for simplicity just assume the target process is 32-bit (like this one). + // c) The current process is not running under WOW64. Since we know it is 32-bit (due to our use + // of conditional compilation), the OS and all running processes must be 32-bit. + return FALSE; +#endif +} + + + +LPVOID AllocInterProcMem(HANDLE &aHandle, DWORD aSize, HWND aHwnd, DWORD aExtraAccess) +// aHandle is an output parameter that receives the process handle. +// Returns NULL on failure (in which case caller should ignore the value of aHandle). +{ + LPVOID mem; + DWORD pid; + GetWindowThreadProcessId(aHwnd, &pid); + // Even if the PID is our own, open the process anyway to simplify the code. After all, it would be + // pretty silly for a script to access its own ListViews via this method. + if ( !(aHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | aExtraAccess, FALSE, pid)) ) + return NULL; // Let ErrorLevel tell the story. + // Reason for using VirtualAllocEx(): When sending LVITEM structures to a control in a remote process, the + // structure and its pszText buffer must both be memory inside the remote process rather than in our own. + mem = VirtualAllocEx(aHandle, NULL, aSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!mem) - CloseHandle(aHandle); // Closes the mapping for Win9x and the process handle for other OSes. Caller should ignore the value of aHandle when return value is NULL. - //else leave the handle open (required for both methods). It's the caller's responsibility to close it. + CloseHandle(aHandle); // Caller should ignore the value of aHandle when return value is NULL. + //else leave the handle open. It's the caller's responsibility to close it. return mem; } void FreeInterProcMem(HANDLE aHandle, LPVOID aMem) -// Caller has ensured that aMem is a file-mapping for Win9x and a VirtualAllocEx block for NT/2k/XP+. -// Similarly, it has ensured that aHandle is a file-mapping handle for Win9x and a process handle for NT/2k/XP+. { - if (g_os.IsWin9x()) - UnmapViewOfFile(aMem); - else - { - // Load function dynamically to allow program to launch on win9x: - typedef BOOL (WINAPI *MyVirtualFreeExType)(HANDLE, LPVOID, SIZE_T, DWORD); - static MyVirtualFreeExType MyVirtualFreeEx = (MyVirtualFreeExType)GetProcAddress(GetModuleHandle(_T("kernel32")) - , "VirtualFreeEx"); - MyVirtualFreeEx(aHandle, aMem, 0, MEM_RELEASE); // Size 0 is used with MEM_RELEASE. - } - // The following closes either the mapping or the process handle, depending on OS type. - // But close it only after the above is done using it. + VirtualFreeEx(aHandle, aMem, 0, MEM_RELEASE); // Size 0 is used with MEM_RELEASE. CloseHandle(aHandle); } HBITMAP LoadPicture(LPTSTR aFilespec, int aWidth, int aHeight, int &aImageType, int aIconNumber , bool aUseGDIPlusIfAvailable) // Returns NULL on failure. // If aIconNumber > 0, an HICON or HCURSOR is returned (both should be interchangeable), never an HBITMAP. // However, aIconNumber==1 is treated as a special icon upon which LoadImage is given preference over ExtractIcon // for .ico/.cur/.ani files. // Otherwise, .ico/.cur/.ani files are normally loaded as HICON (unless aUseGDIPlusIfAvailable is true or // something else unusual happened such as file contents not matching file's extension). This is done to preserve // any properties that HICONs have but HBITMAPs lack, namely the ability to be animated and perhaps other things. // // Loads a JPG/GIF/BMP/ICO/etc. and returns an HBITMAP or HICON to the caller (which it may call // DeleteObject()/DestroyIcon() upon, though upon program termination all such handles are freed // automatically). The image is scaled to the specified width and height. If zero is specified // for either, the image's actual size will be used for that dimension. If -1 is specified for one, // that dimension will be kept proportional to the other dimension's size so that the original aspect // ratio is retained. { HBITMAP hbitmap = NULL; aImageType = -1; // The type of image currently inside hbitmap. Set default value for output parameter as "unknown". if (!*aFilespec) // Allow blank filename to yield NULL bitmap (and currently, some callers do call it this way). return NULL; // Lexikos: Negative values now indicate an icon's integer resource ID. //if (aIconNumber < 0) // Allowed to be called this way by GUI and others (to avoid need for validation of user input there). // aIconNumber = 0; // Use the default behavior, which is "load icon or bitmap, whichever is most appropriate". LPTSTR file_ext = _tcsrchr(aFilespec, '.'); if (file_ext) ++file_ext; // v1.0.43.07: If aIconNumber is zero, caller didn't specify whether it wanted an icon or bitmap. Thus, // there must be some kind of detection for whether ExtractIcon is needed instead of GDIPlus/OleLoadPicture. // Although this could be done by attempting ExtractIcon only after GDIPlus/OleLoadPicture fails (or by // somehow checking the internal nature of the file), for performance and code size, it seems best to not // to incur this extra I/O and instead make only one attempt based on the file's extension. // Must use ExtractIcon() if either of the following is true: // 1) Caller gave an icon index of the second or higher icon in the file. Update for v1.0.43.05: There // doesn't seem to be any reason to allow a caller to explicitly specify ExtractIcon as the method of // loading the *first* icon from a .ico file since LoadImage is likely always superior. This is // because unlike ExtractIcon/Ex, LoadImage: 1) Doesn't distort icons, especially 16x16 icons; 2) is // capable of loading icons other than the first by means of width and height parameters. // 2) The target file is of type EXE/DLL/ICL/CPL/etc. (LoadImage() is documented not to work on those file types). // ICL files (v1.0.43.05): Apparently ICL files are an unofficial file format. Someone on the newsgroups // said that an ICL is an "ICon Library... a renamed 16-bit Windows .DLL (an NE format executable) which // typically contains nothing but a resource section. The ICL extension seems to be used by convention." // L17: Support negative numbers to mean resource IDs. These are supported by the resource extraction method directly, and by ExtractIcon if aIconNumber < -1. bool ExtractIcon_was_used = aIconNumber > 1 || aIconNumber < 0 || (file_ext && ( !_tcsicmp(file_ext, _T("exe")) || !_tcsicmp(file_ext, _T("dll")) || !_tcsicmp(file_ext, _T("icl")) // Icon library: Unofficial dll container, see notes above. || !_tcsicmp(file_ext, _T("cpl")) // Control panel extension/applet (ExtractIcon is said to work on these). || !_tcsicmp(file_ext, _T("scr")) // Screen saver (ExtractIcon should work since these are really EXEs). // v1.0.44: Below are now omitted to reduce code size and improve performance. They are still supported // indirectly because ExtractIcon is attempted whenever LoadImage() fails further below. //|| !_tcsicmp(file_ext, _T("drv")) // Driver (ExtractIcon is said to work on these). //|| !_tcsicmp(file_ext, _T("ocx")) // OLE/ActiveX Control Extension //|| !_tcsicmp(file_ext, _T("vbx")) // Visual Basic Extension //|| !_tcsicmp(file_ext, _T("acm")) // Audio Compression Manager Driver //|| !_tcsicmp(file_ext, _T("bpl")) // Delphi Library (like a DLL?) // Not supported due to rarity, code size, performance, and uncertainty of whether ExtractIcon works on them. // Update for v1.0.44: The following are now supported indirectly because ExtractIcon is attempted whenever // LoadImage() fails further below. //|| !_tcsicmp(file_ext, _T("nil")) // Norton Icon Library //|| !_tcsicmp(file_ext, _T("wlx")) // Total/Windows Commander Lister Plug-in //|| !_tcsicmp(file_ext, _T("wfx")) // Total/Windows Commander File System Plug-in //|| !_tcsicmp(file_ext, _T("wcx")) // Total/Windows Commander Plug-in //|| !_tcsicmp(file_ext, _T("wdx")) // Total/Windows Commander Plug-in )); if (ExtractIcon_was_used) { aImageType = IMAGE_ICON; // L17: Manually extract the most appropriately sized icon resource for the best results. hbitmap = (HBITMAP)ExtractIconFromExecutable(aFilespec, aIconNumber, aWidth, aHeight); // At this time it seems unnecessary to fall back to any of the following methods: /* if (aWidth && aHeight) // Lexikos: Alternate methods that give better results than ExtractIcon. { int icon_index = aIconNumber > 0 ? aIconNumber - 1 : aIconNumber < -1 ? aIconNumber : 0; // Testing shows ExtractIcon retrieves the first icon in the icon group and resizes it to // the system large icon size. In case scripts expect this behaviour, and because it is // debatable which size will actually look better when scaled, use ExtractIconEX only if // a system size is exactly specified. Callers who specifically want the system small or // large icon should call GetSystemMetrics() to get the correct aWidth and aHeight. // For convenience and because the system icon sizes are probably always square, // assume aWidth == -1 is equivalent to aWidth == aHeight (and vice versa). if ((aWidth == GetSystemMetrics(SM_CXSMICON) || aWidth == -1) && (aHeight == GetSystemMetrics(SM_CYSMICON) || aHeight == -1)) { // Retrieve icon via phiconSmall. ExtractIconEx(aFilespec, icon_index, NULL, (HICON*)&hbitmap, 1); } else if ((aWidth == GetSystemMetrics(SM_CXICON) || aWidth == -1) && (aHeight == GetSystemMetrics(SM_CYICON) || aHeight == -1)) { // Retrieve icon via phiconLarge. ExtractIconEx(aFilespec, icon_index, (HICON*)&hbitmap, NULL, 1); } else { UINT icon_id; // This is the simplest method of loading an icon of an arbitrary size. // "However, this function is deprecated not intended for general use." // It is also not documented to support resource IDs, unlike ExtractIcon and ExtractIconEx. if (-1 == PrivateExtractIcons(aFilespec, icon_index, aWidth == -1 ? aHeight : aWidth, aHeight == -1 ? aWidth : aHeight, (HICON*)&hbitmap, &icon_id, 1, 0)) hbitmap = NULL; } } // Lexikos: ExtractIcon supports resource IDs by specifying nIconIndex < -1, where Abs(nIconIndex) // is the resource ID. nIconIndex MUST NOT BE -1, which is used to indicate the total number of // icons should be returned. ExtractIconEx could be used to support ID -1, but it has different // behaviour to ExtractIcon, and the method above should work in most instances. if (!hbitmap) // The other methods failed or were not used. hbitmap = (HBITMAP)ExtractIcon(g_hInstance, aFilespec, aIconNumber > 0 ? aIconNumber - 1 : aIconNumber < -1 ? aIconNumber : 0); // Above: Although it isn't well documented at MSDN, apparently both ExtractIcon() and LoadIcon() // scale the icon to the system's large-icon size (usually 32x32) regardless of the actual size of // the icon inside the file. For this reason, callers should call us in a way that allows us to // give preference to LoadImage() over ExtractIcon() (unless the caller needs to retain backward // compatibility with existing scripts that explicitly specify icon #1 to force the ExtractIcon // method to be used). */ if (hbitmap < (HBITMAP)2) // i.e. it's NULL or 1. Return value of 1 means "incorrect file type". return NULL; // v1.0.44: Fixed to return NULL vs. hbitmap, since 1 is an invalid handle (perhaps rare since no known bugs caused by it). //else continue on below so that the icon can be resized to the caller's specified dimensions. } else if (aIconNumber > 0) // Caller wanted HICON, never HBITMAP, so set type now to enforce that. aImageType = IMAGE_ICON; // Should be suitable for cursors too, since they're interchangeable for the most part. else if (file_ext) // Make an initial guess of the type of image if the above didn't already determine the type. { if (!_tcsicmp(file_ext, _T("ico"))) aImageType = IMAGE_ICON; else if (!_tcsicmp(file_ext, _T("cur")) || !_tcsicmp(file_ext, _T("ani"))) aImageType = IMAGE_CURSOR; else if (!_tcsicmp(file_ext, _T("bmp"))) aImageType = IMAGE_BITMAP; //else for other extensions, leave set to "unknown" so that the below knows to use IPic or GDI+ to load it. } //else same comment as above. if ((aWidth == -1 || aHeight == -1) && (!aWidth || !aHeight)) aWidth = aHeight = 0; // i.e. One dimension is zero and the other is -1, which resolves to the same as "keep original size". bool keep_aspect_ratio = (aWidth == -1 || aHeight == -1); // Caller should ensure that aUseGDIPlusIfAvailable==false when aIconNumber > 0, since it makes no sense otherwise. HINSTANCE hinstGDI = NULL; if (aUseGDIPlusIfAvailable && !(hinstGDI = LoadLibrary(_T("gdiplus")))) // Relies on short-circuit boolean order for performance. aUseGDIPlusIfAvailable = false; // Override any original "true" value as a signal for the section below. if (!hbitmap && aImageType > -1 && !aUseGDIPlusIfAvailable) { // Since image hasn't yet be loaded and since the file type appears to be one supported by // LoadImage() [icon/cursor/bitmap], attempt that first. If it fails, fall back to the other // methods below in case the file's internal contents differ from what the file extension indicates. int desired_width, desired_height; if (keep_aspect_ratio) // Load image at its actual size. It will be rescaled to retain aspect ratio later below. { desired_width = 0; desired_height = 0; } else { desired_width = aWidth; desired_height = aHeight; } // For LoadImage() below: // LR_CREATEDIBSECTION applies only when aImageType == IMAGE_BITMAP, but seems appropriate in that case. // Also, if width and height are non-zero, that will determine which icon of a multi-icon .ico file gets // loaded (though I don't know the exact rules of precedence). // KNOWN LIMITATIONS/BUGS: // LoadImage() fails when requesting a size of 1x1 for an image whose orig/actual size is small (e.g. 1x2). // Unlike CopyImage(), perhaps it detects that division by zero would occur and refuses to do the // calculation rather than providing more code to do a correct calculation that doesn't divide by zero. // For example: // LoadImage() Success: // Gui, Add, Pic, h2 w2, bitmap 1x2.bmp // Gui, Add, Pic, h1 w1, bitmap 4x6.bmp // LoadImage() Failure: // Gui, Add, Pic, h1 w1, bitmap 1x2.bmp // LoadImage() also fails on: // Gui, Add, Pic, h1, bitmap 1x2.bmp // And then it falls back to GDIplus, which in the particular case above appears to traumatize the // parent window (or its picture control), because the GUI window hangs (but not the script) after // doing a FileSelectFolder. For example: // Gui, Add, Button,, FileSelectFile // Gui, Add, Pic, h1, bitmap 1x2.bmp ; Causes GUI window to hang after FileSelectFolder (due to LoadImage failing then falling back to GDIplus; i.e. GDIplus is somehow triggering the problem). // Gui, Show // return // ButtonFileSelectFile: // FileSelectFile, outputvar // return if (hbitmap = (HBITMAP)LoadImage(NULL, aFilespec, aImageType, desired_width, desired_height , LR_LOADFROMFILE | LR_CREATEDIBSECTION)) { // The above might have loaded an HICON vs. an HBITMAP (it has been confirmed that LoadImage() // will return an HICON vs. HBITMAP is aImageType is IMAGE_ICON/CURSOR). Note that HICON and // HCURSOR are identical for most/all Windows API uses. Also note that LoadImage() will load // an icon as a bitmap if the file contains an icon but IMAGE_BITMAP was passed in (at least // on Windows XP). if (!keep_aspect_ratio) // No further resizing is needed. return hbitmap; // Otherwise, continue on so that the image can be resized via a second call to LoadImage(). } // v1.0.40.10: Abort if file doesn't exist so that GDIPlus isn't even attempted. This is done because // loading GDIPlus apparently disrupts the color palette of certain games, at least old ones that use // DirectDraw in 256-color depth. else if (GetFileAttributes(aFilespec) == 0xFFFFFFFF) // For simplicity, we don't check if it's a directory vs. file, since that should be too rare. return NULL; // v1.0.43.07: Also abort if caller wanted an HICON (not an HBITMAP), since the other methods below // can't yield an HICON. else if (aIconNumber > 0) { // UPDATE for v1.0.44: Attempt ExtractIcon in case its some extension that's // was recognized as an icon container (such as AutoHotkeySC.bin) and thus wasn't handled higher above. //hbitmap = (HBITMAP)ExtractIcon(g_hInstance, aFilespec, aIconNumber - 1); // L17: Manually extract the most appropriately sized icon resource for the best results. hbitmap = (HBITMAP)ExtractIconFromExecutable(aFilespec, aIconNumber, aWidth, aHeight); if (hbitmap < (HBITMAP)2) // i.e. it's NULL or 1. Return value of 1 means "incorrect file type". return NULL; ExtractIcon_was_used = true; } //else file exists, so continue on so that the other methods are attempted in case file's contents // differ from what the file extension indicates, or in case the other methods can be successful // even when the above failed. } IPicture *pic = NULL; // Also used to detect whether IPic method was used to load the image. if (!hbitmap) // Above hasn't loaded the image yet, so use the fall-back methods. { // At this point, regardless of the image type being loaded (even an icon), it will // definitely be converted to a Bitmap below. So set the type: aImageType = IMAGE_BITMAP; // Find out if this file type is supported by the non-GDI+ method. This check is not foolproof // since all it does is look at the file's extension, not its contents. However, it doesn't // need to be 100% accurate because its only purpose is to detect whether the higher-overhead // calls to GdiPlus can be avoided. if (aUseGDIPlusIfAvailable || !file_ext || (_tcsicmp(file_ext, _T("jpg")) && _tcsicmp(file_ext, _T("jpeg")) && _tcsicmp(file_ext, _T("gif")))) // Non-standard file type (BMP is already handled above). if (!hinstGDI) // We don't yet have a handle from an earlier call to LoadLibary(). hinstGDI = LoadLibrary(_T("gdiplus")); // If it is suspected that the file type isn't supported, try to use GdiPlus if available. // If it's not available, fall back to the old method in case the filename doesn't properly // reflect its true contents (i.e. in case it really is a JPG/GIF/BMP internally). // If the below LoadLibrary() succeeds, either the OS is XP+ or the GdiPlus extensions have been // installed on an older OS. if (hinstGDI) { // LPVOID and "int" are used to avoid compiler errors caused by... namespace issues? typedef int (WINAPI *GdiplusStartupType)(ULONG_PTR*, LPVOID, LPVOID); typedef VOID (WINAPI *GdiplusShutdownType)(ULONG_PTR); typedef int (WINGDIPAPI *GdipCreateBitmapFromFileType)(LPVOID, LPVOID); typedef int (WINGDIPAPI *GdipCreateHBITMAPFromBitmapType)(LPVOID, LPVOID, DWORD); typedef int (WINGDIPAPI *GdipDisposeImageType)(LPVOID); GdiplusStartupType DynGdiplusStartup = (GdiplusStartupType)GetProcAddress(hinstGDI, "GdiplusStartup"); GdiplusShutdownType DynGdiplusShutdown = (GdiplusShutdownType)GetProcAddress(hinstGDI, "GdiplusShutdown"); GdipCreateBitmapFromFileType DynGdipCreateBitmapFromFile = (GdipCreateBitmapFromFileType)GetProcAddress(hinstGDI, "GdipCreateBitmapFromFile"); GdipCreateHBITMAPFromBitmapType DynGdipCreateHBITMAPFromBitmap = (GdipCreateHBITMAPFromBitmapType)GetProcAddress(hinstGDI, "GdipCreateHBITMAPFromBitmap"); GdipDisposeImageType DynGdipDisposeImage = (GdipDisposeImageType)GetProcAddress(hinstGDI, "GdipDisposeImage"); ULONG_PTR token; Gdiplus::GdiplusStartupInput gdi_input; Gdiplus::GpBitmap *pgdi_bitmap; if (DynGdiplusStartup && DynGdiplusStartup(&token, &gdi_input, NULL) == Gdiplus::Ok) { #ifndef UNICODE WCHAR filespec_wide[MAX_PATH]; ToWideChar(aFilespec, filespec_wide, MAX_PATH); // Dest. size is in wchars, not bytes. if (DynGdipCreateBitmapFromFile(filespec_wide, &pgdi_bitmap) == Gdiplus::Ok) #else if (DynGdipCreateBitmapFromFile(aFilespec, &pgdi_bitmap) == Gdiplus::Ok) #endif { if (DynGdipCreateHBITMAPFromBitmap(pgdi_bitmap, &hbitmap, CLR_DEFAULT) != Gdiplus::Ok) hbitmap = NULL; // Set to NULL to be sure. DynGdipDisposeImage(pgdi_bitmap); // This was tested once to make sure it really returns Gdiplus::Ok. } // The current thought is that shutting it down every time conserves resources. If so, it // seems justified since it is probably called infrequently by most scripts: DynGdiplusShutdown(token); } FreeLibrary(hinstGDI); } else // Using old picture loading method. { // Based on code sample at http://www.codeguru.com/Cpp/G-M/bitmap/article.php/c4935/ HANDLE hfile = CreateFile(aFilespec, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (hfile == INVALID_HANDLE_VALUE) return NULL; DWORD size = GetFileSize(hfile, NULL); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, size); if (!hglobal) { CloseHandle(hfile); return NULL; } LPVOID hlocked = GlobalLock(hglobal); if (!hlocked) { CloseHandle(hfile); GlobalFree(hglobal); return NULL; } // Read the file into memory: ReadFile(hfile, hlocked, size, &size, NULL); GlobalUnlock(hglobal); CloseHandle(hfile); LPSTREAM stream; if (FAILED(CreateStreamOnHGlobal(hglobal, FALSE, &stream)) || !stream) // Relies on short-circuit boolean order. { GlobalFree(hglobal); return NULL; } // Specify TRUE to have it do the GlobalFree() for us. But since the call might fail, it seems best // to free the mem ourselves to avoid uncertainty over what it does on failure: if (FAILED(OleLoadPicture(stream, 0, FALSE, IID_IPicture, (void **)&pic))) pic = NULL; stream->Release(); GlobalFree(hglobal); if (!pic) return NULL; pic->get_Handle((OLE_HANDLE *)&hbitmap); // Above: MSDN: "The caller is responsible for this handle upon successful return. The variable is set // to NULL on failure." if (!hbitmap) { pic->Release(); return NULL; } // Don't pic->Release() yet because that will also destroy/invalidate hbitmap handle. } // IPicture method was used. } // IPicture or GDIPlus was used to load the image, not a simple LoadImage() or ExtractIcon(). // Above has ensured that hbitmap is now not NULL. // Adjust things if "keep aspect ratio" is in effect: if (keep_aspect_ratio) { HBITMAP hbitmap_to_analyze; ICONINFO ii; // Must be declared at this scope level. if (aImageType == IMAGE_BITMAP) hbitmap_to_analyze = hbitmap; else // icon or cursor { if (GetIconInfo((HICON)hbitmap, &ii)) // Works on cursors too. hbitmap_to_analyze = ii.hbmMask; // Use Mask because MSDN implies hbmColor can be NULL for monochrome cursors and such. else { DestroyIcon((HICON)hbitmap); return NULL; // No need to call pic->Release() because since it's an icon, we know IPicture wasn't used (it only loads bitmaps). } } // Above has ensured that hbitmap_to_analyze is now not NULL. Find bitmap's dimensions. BITMAP bitmap; GetObject(hbitmap_to_analyze, sizeof(BITMAP), &bitmap); // Realistically shouldn't fail at this stage. if (aHeight == -1) { // Caller wants aHeight calculated based on the specified aWidth (keep aspect ratio). if (bitmap.bmWidth) // Avoid any chance of divide-by-zero. aHeight = (int)(((double)bitmap.bmHeight / bitmap.bmWidth) * aWidth + .5); // Round. } else { // Caller wants aWidth calculated based on the specified aHeight (keep aspect ratio). if (bitmap.bmHeight) // Avoid any chance of divide-by-zero. aWidth = (int)(((double)bitmap.bmWidth / bitmap.bmHeight) * aHeight + .5); // Round. } if (aImageType != IMAGE_BITMAP) { // It's our responsibility to delete these two when they're no longer needed: DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); // If LoadImage() vs. ExtractIcon() was used originally, call LoadImage() again because // I haven't found any other way to retain an animated cursor's animation (and perhaps // other icon/cursor attributes) when resizing the icon/cursor (CopyImage() doesn't // retain animation): if (!ExtractIcon_was_used) { DestroyIcon((HICON)hbitmap); // Destroy the original HICON. // Load a new one, but at the size newly calculated above. // Due to an apparent bug in Windows 9x (at least Win98se), the below call will probably // crash the program with a "divide error" if the specified aWidth and/or aHeight are // greater than 90. Since I don't know whether this affects all versions of Windows 9x, and // all animated cursors, it seems best just to document it here and in the help file rather // than limiting the dimensions of .ani (and maybe .cur) files for certain operating systems. return (HBITMAP)LoadImage(NULL, aFilespec, aImageType, aWidth, aHeight, LR_LOADFROMFILE); } } } HBITMAP hbitmap_new; // To hold the scaled image (if scaling is needed). if (pic) // IPicture method was used. { // The below statement is confirmed by having tested that DeleteObject(hbitmap) fails // if called after pic->Release(): // "Copy the image. Necessary, because upon pic's release the handle is destroyed." // MSDN: CopyImage(): "[If either width or height] is zero, then the returned image will have the // same width/height as the original." // Note also that CopyImage() seems to provide better scaling quality than using MoveWindow() // (followed by redrawing the parent window) on the static control that contains it: hbitmap_new = (HBITMAP)CopyImage(hbitmap, IMAGE_BITMAP, aWidth, aHeight // We know it's IMAGE_BITMAP in this case. , (aWidth || aHeight) ? 0 : LR_COPYRETURNORG); // Produce original size if no scaling is needed. pic->Release(); // No need to call DeleteObject(hbitmap), see above. } else // GDIPlus or a simple method such as LoadImage or ExtractIcon was used. { if (!aWidth && !aHeight) // No resizing needed. return hbitmap; // The following will also handle HICON/HCURSOR correctly if aImageType == IMAGE_ICON/CURSOR. // Also, LR_COPYRETURNORG|LR_COPYDELETEORG is used because it might allow the animation of // a cursor to be retained if the specified size happens to match the actual size of the // cursor. This is because normally, it seems that CopyImage() omits cursor animation // from the new object. MSDN: "LR_COPYRETURNORG returns the original hImage if it satisfies // the criteria for the copy—that is, correct dimensions and color depth—in which case the // LR_COPYDELETEORG flag is ignored. If this flag is not specified, a new object is always created." // KNOWN BUG: Calling CopyImage() when the source image is tiny and the destination width/height // is also small (e.g. 1) causes a divide-by-zero exception. // For example: // Gui, Add, Pic, h1 w-1, bitmap 1x2.bmp ; Crash (divide by zero) // Gui, Add, Pic, h1 w-1, bitmap 2x3.bmp ; Crash (divide by zero) // However, such sizes seem too rare to document or put in an exception handler for. hbitmap_new = (HBITMAP)CopyImage(hbitmap, aImageType, aWidth, aHeight, LR_COPYRETURNORG | LR_COPYDELETEORG); // Above's LR_COPYDELETEORG deletes the original to avoid cascading resource usage. MSDN's // LoadImage() docs say: // "When you are finished using a bitmap, cursor, or icon you loaded without specifying the // LR_SHARED flag, you can release its associated memory by calling one of [the three functions]." // Therefore, it seems best to call the right function even though DeleteObject might work on // all of them on some or all current OSes. UPDATE: Evidence indicates that DestroyIcon() // will also destroy cursors, probably because icons and cursors are literally identical in // every functional way. One piece of evidence: //> No stack trace, but I know the exact source file and line where the call //> was made. But still, it is annoying when you see 'DestroyCursor' even though //> there is 'DestroyIcon'. // "Can't be helped. Icons and cursors are the same thing" (Tim Robinson (MVP, Windows SDK)). // // Finally, the reason this is important is that it eliminates one handle type // that we would otherwise have to track. For example, if a gui window is destroyed and // and recreated multiple times, its bitmap and icon handles should all be destroyed each time. // Otherwise, resource usage would cascade upward until the script finally terminated, at // which time all such handles are freed automatically. } return hbitmap_new; } struct ResourceIndexToIdEnumData { int find_index; int index; int result; }; BOOL CALLBACK ResourceIndexToIdEnumProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam) { ResourceIndexToIdEnumData &enum_data = *(ResourceIndexToIdEnumData*)lParam; if (++enum_data.index == enum_data.find_index) { enum_data.result = (int)lpszName; return FALSE; // Stop } return TRUE; // Continue } // L17: Find integer ID of resource from one-based index. i.e. IconNumber -> resource ID. int ResourceIndexToId(HMODULE aModule, LPCTSTR aType, int aIndex) { ResourceIndexToIdEnumData enum_data; enum_data.find_index = aIndex; enum_data.index = 0; enum_data.result = -1; // Return value of -1 indicates failure, since ID 0 may be valid. EnumResourceNames(aModule, aType, &ResourceIndexToIdEnumProc, (LONG_PTR)&enum_data); return enum_data.result; } // L17: Extract icon of the appropriate size from an executable (or compatible) file. HICON ExtractIconFromExecutable(LPTSTR aFilespec, int aIconNumber, int aWidth, int aHeight) { HICON hicon = NULL; // If the module is already loaded as an executable, LoadLibraryEx returns its handle. // Otherwise each call will receive its own handle to a data file mapping. HMODULE hdatafile = LoadLibraryEx(aFilespec, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hdatafile) { int group_icon_id = (aIconNumber < 0 ? -aIconNumber : ResourceIndexToId(hdatafile, (LPCTSTR)RT_GROUP_ICON, aIconNumber ? aIconNumber : 1)); HRSRC hres; HGLOBAL hresdata; LPVOID presdata; // MSDN indicates resources are unloaded when the *process* exits, but also states // that the pointer returned by LockResource is valid until the *module* containing // the resource is unloaded. Testing seems to indicate that unloading a module indeed // unloads or invalidates any resources it contains. if ((hres = FindResource(hdatafile, MAKEINTRESOURCE(group_icon_id), RT_GROUP_ICON)) && (hresdata = LoadResource(hdatafile, hres)) && (presdata = LockResource(hresdata))) { // LookupIconIdFromDirectoryEx seems to use whichever is larger of aWidth or aHeight, // so one or the other may safely be -1. However, since this behaviour is undocumented, // treat -1 as "same as other dimension": int icon_id = LookupIconIdFromDirectoryEx((PBYTE)presdata, TRUE, aWidth == -1 ? aHeight : aWidth, aHeight == -1 ? aWidth : aHeight, 0); if (icon_id diff --git a/source/util.h b/source/util.h index 088e72a..6deb773 100644 --- a/source/util.h +++ b/source/util.h @@ -240,533 +240,534 @@ inline size_t omit_trailing_any(LPTSTR aBuf, LPTSTR aOmitList, LPTSTR aBuf_marke } inline size_t ltrim(LPTSTR aStr, size_t aLength = -1) // Caller must ensure that aStr is not NULL. // v1.0.25: Returns the length if it was discovered as a result of the operation, or aLength otherwise. // This greatly improves the performance of PerformAssign(). // NOTE: THIS VERSION trims only tabs and spaces. It specifically avoids // trimming newlines because some callers want to retain those. { if (!*aStr) return 0; LPTSTR ptr; // Find the first non-whitespace char (which might be the terminator): for (ptr = aStr; IS_SPACE_OR_TAB(*ptr); ++ptr); // Self-contained loop. // v1.0.25: If no trimming needed, don't do the memmove. This seems to make a big difference // in the performance of critical sections of the program such as PerformAssign(): size_t offset; if (offset = ptr - aStr) // Assign. { if (aLength == -1) aLength = _tcslen(ptr); // Set aLength as new/trimmed length, for use below and also as the return value. else // v1.0.25.05 bug-fix: Must adjust the length provided by caller to reflect what we did here. aLength -= offset; tmemmove(aStr, ptr, aLength + 1); // +1 to include the '\0'. memmove() permits source & dest to overlap. } return aLength; // This will return -1 if the block above didn't execute and caller didn't specify the length. } inline size_t rtrim(LPTSTR aStr, size_t aLength = -1) // Caller must ensure that aStr is not NULL. // To improve performance, caller may specify a length (e.g. when it is already known). // v1.0.25: Always returns the new length of the string. This greatly improves the performance of // PerformAssign(). // NOTE: THIS VERSION trims only tabs and spaces. It specifically avoids trimming newlines because // some callers want to retain those. { if (!*aStr) return 0; // The below relies upon this check having been done. // It's done this way in case aStr just happens to be address 0x00 (probably not possible // on Intel & Intel-clone hardware) because otherwise --cp would decrement, causing an // underflow since pointers are probably considered unsigned values, which would // probably cause an infinite loop. Extremely unlikely, but might as well try // to be thorough: if (aLength == -1) aLength = _tcslen(aStr); // Set aLength for use below and also as the return value. for (LPTSTR cp = aStr + aLength - 1; ; --cp, --aLength) { if (!IS_SPACE_OR_TAB(*cp)) { cp[1] = '\0'; return aLength; } // Otherwise, it is a space or tab... if (cp == aStr) // ... and we're now at the first character of the string... { if (IS_SPACE_OR_TAB(*cp)) // ... and that first character is also a space or tab... { *cp = '\0'; // ... so the entire string is made empty... return 0; // Fix for v1.0.39: Must return 0 not aLength in this case. } return aLength; // ... and we return in any case. } // else it's a space or tab, and there are still more characters to check. Let the loop // do its decrements. } } inline void rtrim_literal(LPTSTR aStr, TCHAR aLiteralMap[]) // Caller must ensure that aStr is not NULL. // NOTE: THIS VERSION trims only tabs and spaces which aren't marked as literal (so not "`t" or "` "). // It specifically avoids trimming newlines because some callers want to retain those. { if (!*aStr) return; // The below relies upon this check having been done. // It's done this way in case aStr just happens to be address 0x00 (probably not possible // on Intel & Intel-clone hardware) because otherwise --cp would decrement, causing an // underflow since pointers are probably considered unsigned values, which would // probably cause an infinite loop. Extremely unlikely, but might as well try // to be thorough: for (size_t last = _tcslen(aStr) - 1; ; --last) { if (!IS_SPACE_OR_TAB(aStr[last]) || aLiteralMap[last]) // It's not a space or tab, or it's a literal one. { aStr[last + 1] = '\0'; return; } // Otherwise, it is a space or tab... if (last == 0) // ... and we're now at the first character of the string... { if (IS_SPACE_OR_TAB(aStr[last])) // ... and that first character is also a space or tab... *aStr = '\0'; // ... so the entire string is made empty. return; // ... and we return in any case. } // else it's a space or tab, and there are still more characters to check. Let the loop // do its decrements. } } inline size_t rtrim_with_nbsp(LPTSTR aStr, size_t aLength = -1) // Returns the new length of the string. // Caller must ensure that aStr is not NULL. // To improve performance, caller may specify a length (e.g. when it is already known). // Same as rtrim but also gets rid of those annoying nbsp (non breaking space) chars that sometimes // wind up on the clipboard when copied from an HTML document, and thus get pasted into the text // editor as part of the code (such as the sample code in some of the examples). { if (!*aStr) return 0; // The below relies upon this check having been done. if (aLength == -1) aLength = _tcslen(aStr); // Set aLength for use below and also as the return value. for (LPTSTR cp = aStr + aLength - 1; ; --cp, --aLength) { if (!IS_SPACE_OR_TAB_OR_NBSP(*cp)) { cp[1] = '\0'; return aLength; } if (cp == aStr) { if (IS_SPACE_OR_TAB_OR_NBSP(*cp)) // ... and that first character is also a space or tab... { *cp = '\0'; // ... so the entire string is made empty... return 0; // Fix for v1.0.39: Must return 0 not aLength in this case. } return aLength; // ... and we return in any case. } } } inline size_t trim(LPTSTR aStr, size_t aLength = -1) // Caller must ensure that aStr is not NULL. // Returns new length of aStr. // To improve performance, caller may specify a length (e.g. when it is already known). // NOTE: THIS VERSION trims only tabs and spaces. It specifically avoids // trimming newlines because some callers want to retain those. { aLength = ltrim(aStr, aLength); // It may return -1 to indicate that it still doesn't know the length. return rtrim(aStr, aLength); // v1.0.25: rtrim() always returns the new length of the string. This greatly improves the // performance of PerformAssign() and possibly other things. } inline size_t strip_trailing_backslash(LPTSTR aPath) // Removes any backslash (if there is one). // Returns length of the new string to allow some callers to avoid another strlen() call. { size_t length = _tcslen(aPath); if (!length) // Below relies on this check having been done to prevent underflow. return length; LPTSTR cp = aPath + length - 1; if (*cp == _T('\\')) { *cp = '\0'; return length - 1; } // Otherwise there no slash to remove, so return the current length. return length; } // Transformation is the same in either direction because the end bytes are swapped // and the middle byte is left as-is: #define bgr_to_rgb(aBGR) rgb_to_bgr(aBGR) inline COLORREF rgb_to_bgr(DWORD aRGB) // Fancier methods seem prone to problems due to byte alignment or compiler issues. { return RGB(GetBValue(aRGB), GetGValue(aRGB), GetRValue(aRGB)); } inline bool IsHex(LPCTSTR aBuf) // 10/17/2006: __forceinline worsens performance, but physically ordering it near ATOI64() [via /ORDER] boosts by 3.5%. // Note: AHK support for hex ints reduces performance by only 10% for decimal ints, even in the tightest // of math loops that have SetBatchLines set to -1. { // For whatever reason, omit_leading_whitespace() benches consistently faster (albeit slightly) than // the same code put inline (confirmed again on 10/17/2006, though the difference is hardly anything): //for (; IS_SPACE_OR_TAB(*aBuf); ++aBuf); aBuf = omit_leading_whitespace(aBuf); // i.e. caller doesn't have to have ltrimmed. if (!*aBuf) return false; if (*aBuf == '-' || *aBuf == '+') ++aBuf; // The "0x" prefix must be followed by at least one hex digit, otherwise it's not considered hex: #define IS_HEX(buf) (*buf == '0' && (*(buf + 1) == 'x' || *(buf + 1) == 'X') && isxdigit(*(buf + 2))) return IS_HEX(aBuf); } // As of v1.0.30, ATOI(), ITOA() and the other related functions below are no longer macros // because there are too many places where something like ATOI(++cp) is done, which would be a // bug if not caught since cp would be incremented more than once if the macro referred to that // arg more than once. In addition, a non-comprehensive, simple benchmark shows that the // macros don't perform any better anyway, probably in part because there are many times when // something like ArgToInt(1) is called, which forces the ARG1 macro to be expanded two or more // times within ATOI (when it was a macro). So for now, the below are declared as inline. // However, it seems that the compiler chooses not to make them truly inline, which as it // turns out is probably the right decision since a simple benchmark shows that even with // __forceinline in effect for all of them (which is confirmed to actually force inline), // the performance isn't any better. inline __int64 ATOI64(LPCTSTR buf) // The following comment only applies if the code is a macro or actually put inline by the compiler, // which is no longer true: // A more complex macro is used for ATOI64(), since it is more often called from places where // performance matters (e.g. ACT_ADD). It adds about 500 bytes to the code size in exchange for // a 8% faster math loops. But it's probably about 8% slower when used with hex integers, but // those are so rare that the speed-up seems worth the extra code size: //#define ATOI64(buf) _strtoi64(buf, NULL, 0) // formerly used _atoi64() { return IsHex(buf) ? _tcstoi64(buf, NULL, 16) : _ttoi64(buf); // _atoi64() has superior performance, so use it when possible. } inline unsigned __int64 ATOU64(LPCTSTR buf) { return _tcstoui64(buf, NULL, IsHex(buf) ? 16 : 10); } inline int ATOI(LPCTSTR buf) { // Below has been updated because values with leading zeros were being interpreted as // octal, which is undesirable. // Formerly: #define ATOI(buf) strtol(buf, NULL, 0) // Use zero as last param to support both hex & dec. return IsHex(buf) ? _tcstol(buf, NULL, 16) : _ttoi(buf); // atoi() has superior performance, so use it when possible. } // v1.0.38.01: Make ATOU a macro that refers to ATOI64() to improve performance (takes advantage of _atoi64() // being considerably faster than strtoul(), at least when the number is non-hex). This relies on the fact // that ATOU() and (UINT)ATOI64() produce the same result due to the way casting works. For example: // ATOU("-1") == (UINT)ATOI64("-1") // ATOU("-0xFFFFFFFF") == (UINT)ATOI64("-0xFFFFFFFF") #define ATOU(buf) (UINT)ATOI64(buf) //inline unsigned long ATOU(char *buf) //{ // // As a reminder, strtoul() also handles negative numbers. For example, ATOU("-1") is // // 4294967295 (0xFFFFFFFF) and ATOU("-2") is 4294967294. // return strtoul(buf, NULL, IsHex(buf) ? 16 : 10); //} inline double ATOF(LPCTSTR buf) // Unlike some Unix versions of strtod(), the VC++ version does not seem to handle hex strings // such as "0xFF" automatically. So this macro must check for hex because some callers rely on that. // Also, it uses _strtoi64() vs. strtol() so that more of a double's capacity can be utilized: { return IsHex(buf) ? (double)_tcstoi64(buf, NULL, 16) : _tstof(buf); } inline LPTSTR ITOA(int value, LPTSTR buf) { if (g->FormatInt == 'D') { return _itot(value, buf, 10); } // g->FormatInt == 'h' or 'H' LPTSTR our_buf_temp = buf; // Negative hex numbers need special handling, otherwise something like zero minus one would create // a huge 0xffffffffffffffff value, which would subsequently not be read back in correctly as // a negative number (but UTOA() doesn't need this since there can't be negatives in that case). if (value < 0) { *our_buf_temp++ = '-'; value = -value; } *our_buf_temp++ = '0'; *our_buf_temp++ = 'x'; _itot(value, our_buf_temp, 16); // Must not return the result of the above because it's our_buf_temp and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(our_buf_temp); return buf; } inline LPTSTR ITOA64(__int64 value, LPTSTR buf) { if (g->FormatInt == 'D') { return _i64tot(value, buf, 10); } // g->FormatInt == 'h' or 'H' LPTSTR our_buf_temp = buf; if (value < 0) { *our_buf_temp++ = '-'; value = -value; } *our_buf_temp++ = '0'; *our_buf_temp++ = 'x'; _i64tot(value, our_buf_temp, 16); // Must not return the result of the above because it's our_buf_temp and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(our_buf_temp); return buf; } inline LPTSTR UTOA(unsigned long value, LPTSTR buf) { if (g->FormatInt == 'D') { return _ultot(value, buf, 10); } // g->FormatInt == 'h' or 'H' *buf = '0'; *(buf + 1) = 'x'; _ultot(value, buf + 2, 16); // Must not return the result of the above because it's buf + 2 and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(buf + 2); return buf; } #ifdef _WIN64 inline LPTSTR UTOA64(unsigned __int64 value, LPTSTR buf) { if (g->FormatInt == 'D') { return _ui64tot(value, buf, 10); } // g->FormatInt == 'h' or 'H' *buf = '0'; *(buf + 1) = 'x'; _ui64tot(value, buf + 2, 16); // Must not return the result of the above because it's buf + 2 and we want buf. if (g->FormatInt == 'H') // uppercase CharUpper(buf + 2); return buf; } #endif inline LPTSTR HwndToString(HWND aHwnd, LPTSTR aBuf) { aBuf[0] = '0'; aBuf[1] = 'x'; // Use _ultot for performance on 32-bit systems and _ui64tot on 64-bit systems in case it's // possible for HWNDs to have non-zero upper 32-bits: Exp32or64(_ultot,_ui64tot)((size_t)aHwnd, aBuf + 2, 16); return aBuf; } //inline LPTSTR tcscatmove(LPTSTR aDst, LPCTSTR aSrc) //// Same as strcat() but allows aSrc and aDst to overlap. //// Unlike strcat(), it doesn't return aDst. Instead, it returns the position //// in aDst where aSrc was appended. //{ // if (!aDst || !aSrc || !*aSrc) return aDst; // LPTSTR aDst_end = aDst + _tcslen(aDst); // return (LPTSTR)memmove(aDst_end, aSrc, (_tcslen(aSrc) + 1) * sizeof(TCHAR)); // Add 1 to include aSrc's terminator. //} // v1.0.43.03: The following macros support the new "StringCaseSense Locale" setting. This setting performs // 1 to 10 times slower for most things, but has the benefit of seeing characters like ä and Ä as identical // when insensitive. MSDN implies that lstrcmpi() is the same as: // CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, ...) // Note that when MSDN talks about the "word sort" vs. "string sort", it does not mean that strings like // "co-op" and "co-op" are considered equal. Instead, they are considered closer together than the traditional // string sort would see them, so that they wind up together in a sorted list. // And both of them benchmark the same, so lstrcmpi is now used here and in various other places throughout // the program when the new locale-case-insensitive mode is in effect. #define tcscmp2(str1, str2, string_case_sense) ((string_case_sense) == SCS_INSENSITIVE ? _tcsicmp(str1, str2) \ : ((string_case_sense) == SCS_INSENSITIVE_LOCALE ? lstrcmpi(str1, str2) : _tcscmp(str1, str2))) #define g_tcscmp(str1, str2) tcscmp2(str1, str2, ::g->StringCaseSense) // The most common mode is listed first for performance: #define tcsstr2(haystack, needle, string_case_sense) ((string_case_sense) == SCS_INSENSITIVE ? tcscasestr(haystack, needle) \ : ((string_case_sense) == SCS_INSENSITIVE_LOCALE ? lstrcasestr(haystack, needle) : _tcsstr(haystack, needle))) #define g_tcsstr(haystack, needle) tcsstr2(haystack, needle, ::g->StringCaseSense) // For the following, caller must ensure that len1 and len2 aren't beyond the terminated length of the string // because CompareString() might not stop at the terminator when a length is specified. Also, CompareString() // returns 0 on failure, but failure occurs only when parameter/flag is invalid, which should never happen in // this case. #define lstrcmpni(str1, len1, str2, len2) (CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, str1, (int)(len1), str2, (int)(len2)) - 2) // -2 for maintainability // The following macros simplify and make consistent the calls to MultiByteToWideChar(). // MSDN implies that passing -1 for cbMultiByte is the most typical and secure usage because it ensures // that the output is null-terminated: "the resulting wide character string has a null terminator, and the // length returned by the function includes the terminating null character." // // I couldn't find any info on when MB_PRECOMPOSED is needed (if ever). It's the default anyway, // which implies that passing zero (which is quite common in many examples I've seen) is essentially // the same as passing MB_PRECOMPOSED. However, some modes such as CP_UTF8 should never use MB_PRECOMPOSED // or the function will fail. // // #1: FROM ANSI TO UNICODE (UTF-16). dest_size_in_wchars includes the terminator. // From looking at the source to mbstowcs(), it might be faster when the "C" locale is in effect (which is // the default in the absence of setlocale()) than MultiByteToWideChar() depending on how the latter is // implemented. This is because mbstowcs() simply casts the characters to (wchar_t)(unsigned char) without // any other translation at all. Although that behavior is probably identical to MultiByteToWideChar(CP_ACP...), // it's not completely certain -- so it seems best to stick with MultiByteToWideChar() for consistency // (also, avoiding mbstowcs slightly reduces code size). If there's ever a case where performance is // important, create a simple casting loop (see mbstowcs.c for an example) that converts source to dest, // and test if it performs significantly better than MultiByteToWideChar(CP_ACP...). #define ToWideChar(source, dest, dest_size_in_wchars) MultiByteToWideChar(CP_ACP, 0, source, -1, dest, dest_size_in_wchars) // // #2: FROM UTF-8 TO UNICODE (UTF-16). dest_size_in_wchars includes the terminator. MSDN: "For UTF-8, dwFlags must be set to either 0 or MB_ERR_INVALID_CHARS. Otherwise, the function fails with ERROR_INVALID_FLAGS." #define UTF8ToWideChar(source, dest, dest_size_in_wchars) MultiByteToWideChar(CP_UTF8, 0, source, -1, dest, dest_size_in_wchars) // // #3: FROM UNICODE (UTF-16) TO UTF-8. dest_size_in_bytes includes the terminator. #define WideCharToUTF8(source, dest, dest_size_in_bytes) WideCharToMultiByte(CP_UTF8, 0, source, -1, dest, dest_size_in_bytes, NULL, NULL) #define UTF8StrLen(str, cch) MultiByteToWideChar(CP_UTF8, 0, (str), (cch), NULL, 0) #define WideUTF8StrLen(str, cch) WideCharToMultiByte(CP_UTF8, 0, (str), (cch), NULL, 0, NULL, NULL) #ifdef UNICODE #define PosToUTF8Pos WideUTF8StrLen #define LenToUTF8Len(str,pos,len) WideUTF8StrLen(LPCWSTR(str)+int(pos),len) #define UTF8PosToPos UTF8StrLen #define UTF8LenToLen(str,pos,len) UTF8StrLen(LPCSTR(str)+int(pos),len) inline char* WideToUTF8(LPCWSTR str){ int buf_len = WideCharToUTF8(str, NULL, 0); LPSTR buf = (LPSTR) malloc(buf_len); if (buf) WideCharToUTF8(str, buf, buf_len); return buf; } inline LPTSTR UTF8ToWide(LPCSTR str){ int buf_len = UTF8ToWideChar(str, NULL, 0); LPTSTR buf = (LPTSTR) tmalloc(buf_len); if (buf) UTF8ToWideChar(str, buf, buf_len); return buf; } #endif #ifdef UNICODE #define UorA(u,a) (u) //#define TPosToUTF8Pos PosToUTF8Pos //#define TLenToUTF8Len LenToUTF8Len //#define UTF8PosToTPos UTF8PosToPos //#define UTF8LenToTLen UTF8LenToLen #define ToUnicodeOrAsciiEx(wVirtKey, wScanCode, lpKeyState, pszBuff, wFlags, dwhkl) \ ToUnicodeEx((wVirtKey), (wScanCode), (lpKeyState), (LPWSTR)(pszBuff), 2, (wFlags), (dwhkl)) #else #define UorA(u,a) (a) //#define TPosToUTF8Pos(a,b) (b) //#define TLenToUTF8Len(a,b,c) (c) //#define UTF8PosToTPos(a,b) (b) //#define UTF8LenToTLen(a,b,c) (c) #define ToUnicodeOrAsciiEx(wVirtKey, wScanCode, lpKeyState, pszBuff, wFlags, dwhkl) \ ToAsciiEx((wVirtKey), (wScanCode), (lpKeyState), (LPWORD)(pszBuff), (wFlags), (dwhkl)) #endif // v1.0.44.03: Callers now use the following macro rather than the old approach. However, this change // is meaningful only to people who use more than one keyboard layout. In the case of hotstrings: // It seems that the vast majority of them would want the Hotstring monitoring to adhere to the active // window's current keyboard layout rather than the script's. This change is somewhat less certain to // be desirable unconditionally for the Input command (especially invisible/non-V-option Inputs); but it // seems best to use the same approach to avoid calling ToAsciiEx() more than once in cases where a // script has hotstrings and also uses the Input command. Calling ToAsciiEx() twice in such a case would // be likely to aggravate its side effects with dead keys as described at length in the hook/Input code). #define Get_active_window_keybd_layout \ HWND active_window;\ HKL active_window_keybd_layout = GetKeyboardLayout((active_window = GetForegroundWindow())\ ? GetWindowThreadProcessId(active_window, NULL) : 0); // When no foreground window, the script's own layout seems like the safest default. #define FONT_POINT(hdc, p) (-MulDiv(p, GetDeviceCaps(hdc, LOGPIXELSY), 72)) #define DATE_FORMAT_LENGTH 14 // "YYYYMMDDHHMISS" #define IS_LEAP_YEAR(year) ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) int GetYDay(int aMon, int aDay, bool aIsLeapYear); int GetISOWeekNumber(LPTSTR aBuf, int aYear, int aYDay, int aWDay); ResultType YYYYMMDDToFileTime(LPTSTR aYYYYMMDD, FILETIME &aFileTime); DWORD YYYYMMDDToSystemTime2(LPTSTR aYYYYMMDD, SYSTEMTIME *aSystemTime); ResultType YYYYMMDDToSystemTime(LPTSTR aYYYYMMDD, SYSTEMTIME &aSystemTime, bool aDoValidate); LPTSTR FileTimeToYYYYMMDD(LPTSTR aBuf, FILETIME &aTime, bool aConvertToLocalTime = false); LPTSTR SystemTimeToYYYYMMDD(LPTSTR aBuf, SYSTEMTIME &aTime); __int64 YYYYMMDDSecondsUntil(LPTSTR aYYYYMMDDStart, LPTSTR aYYYYMMDDEnd, bool &aFailed); __int64 FileTimeSecondsUntil(FILETIME *pftStart, FILETIME *pftEnd); SymbolType IsPureNumeric(LPCTSTR aBuf, BOOL aAllowNegative = false // BOOL vs. bool might squeeze a little more performance out of this frequently-called function. , BOOL aAllowAllWhitespace = true, BOOL aAllowFloat = false, BOOL aAllowImpure = false); void strlcpy(LPSTR aDst, LPCSTR aSrc, size_t aDstSize); void wcslcpy(LPWSTR aDst, LPCWSTR aSrc, size_t aDstSize); #ifdef UNICODE #define tcslcpy wcslcpy #else #define tcslcpy strlcpy #endif int sntprintf(LPTSTR aBuf, int aBufSize, LPCTSTR aFormat, ...); int sntprintfcat(LPTSTR aBuf, int aBufSize, LPCTSTR aFormat, ...); // Not currently used by anything, so commented out to possibly reduce code size: //int tcslcmp (LPTSTR aBuf1, LPTSTR aBuf2, UINT aLength1 = UINT_MAX, UINT aLength2 = UINT_MAX); int tcslicmp(LPTSTR aBuf1, LPTSTR aBuf2, size_t aLength1 = -1, size_t aLength2 = -1); LPTSTR tcsrstr(LPTSTR aStr, size_t aStr_length, LPCTSTR aPattern, StringCaseSenseType aStringCaseSense, int aOccurrence = 1); LPTSTR lstrcasestr(LPCTSTR phaystack, LPCTSTR pneedle); LPTSTR tcscasestr (LPCTSTR phaystack, LPCTSTR pneedle); UINT StrReplace(LPTSTR aHaystack, LPTSTR aOld, LPTSTR aNew, StringCaseSenseType aStringCaseSense , UINT aLimit = UINT_MAX, size_t aSizeLimit = -1, LPTSTR *aDest = NULL, size_t *aHaystackLength = NULL); size_t PredictReplacementSize(ptrdiff_t aLengthDelta, int aReplacementCount, int aLimit, size_t aHaystackLength , size_t aCurrentLength, size_t aEndOffsetOfCurrMatch); LPTSTR TranslateLFtoCRLF(LPTSTR aString); bool DoesFilePatternExist(LPTSTR aFilePattern, DWORD *aFileAttr = NULL); #ifdef _DEBUG ResultType FileAppend(LPTSTR aFilespec, LPTSTR aLine, bool aAppendNewline = true); #endif LPTSTR ConvertFilespecToCorrectCase(LPTSTR aFullFileSpec); LPTSTR FileAttribToStr(LPTSTR aBuf, DWORD aAttr); unsigned __int64 GetFileSize64(HANDLE aFileHandle); LPTSTR GetLastErrorText(LPTSTR aBuf, int aBufSize, bool aUpdateLastError = false); void AssignColor(LPTSTR aColorName, COLORREF &aColor, HBRUSH &aBrush); COLORREF ColorNameToBGR(LPTSTR aColorName); HRESULT MySetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName, LPCWSTR pszSubIdList); //HRESULT MyEnableThemeDialogTexture(HWND hwnd, DWORD dwFlags); LPTSTR ConvertEscapeSequences(LPTSTR aBuf, TCHAR aEscapeChar, bool aAllowEscapedSpace); int FindNextDelimiter(LPCTSTR aBuf, TCHAR aDelimiter = ',', int aStartIndex = 0, LPCTSTR aLiteralMap = NULL); POINT CenterWindow(int aWidth, int aHeight); bool FontExist(HDC aHdc, LPCTSTR aTypeface); void ScreenToWindow(POINT &aPoint, HWND aHwnd); void CoordToScreen(int &aX, int &aY, int aWhichMode); void CoordToScreen(POINT &aPoint, int aWhichMode); void GetVirtualDesktopRect(RECT &aRect); -LPVOID AllocInterProcMem(HANDLE &aHandle, DWORD aSize, HWND aHwnd); +BOOL IsProcess64Bit(HANDLE aHandle); +LPVOID AllocInterProcMem(HANDLE &aHandle, DWORD aSize, HWND aHwnd, DWORD aExtraAccess = 0); void FreeInterProcMem(HANDLE aHandle, LPVOID aMem); DWORD GetEnvVarReliable(LPCTSTR aEnvVarName, LPTSTR aBuf); DWORD ReadRegString(HKEY aRootKey, LPTSTR aSubkey, LPTSTR aValueName, LPTSTR aBuf, DWORD aBufSize); HBITMAP LoadPicture(LPTSTR aFilespec, int aWidth, int aHeight, int &aImageType, int aIconNumber , bool aUseGDIPlusIfAvailable); HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon); HBITMAP IconToBitmap32(HICON aIcon, bool aDestroyIcon); // Lexikos: Used for menu icons on Vista+. Creates a 32-bit (ARGB) device-independent bitmap from an icon. int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); bool IsStringInList(LPTSTR aStr, LPTSTR aList, bool aFindExactMatch); int ResourceIndexToId(HMODULE aModule, LPCTSTR aType, int aIndex); // L17: Find integer ID of resource from index. i.e. IconNumber -> resource ID. HICON ExtractIconFromExecutable(LPTSTR aFilespec, int aIconNumber, int aWidth, int aHeight); // L17: Extract icon of the appropriate size from an executable (or compatible) file. #if defined(_MSC_VER) && defined(_DEBUG) void OutputDebugStringFormat(LPCTSTR fmt, ...); // put debug message to the "Output" panel of Visual Studio. #endif #endif
tinku99/ahkdll
9214373e07a66f1041a5cd603d6c23c24a00aacc
Fixed Input not to shrink variable when input is empty (multithreading issue)
diff --git a/source/script2.cpp b/source/script2.cpp index 61069e1..cd7ccf8 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -1144,1174 +1144,1191 @@ end_get_length: SET_HTML_ENTITY("&lt;"); break; case '>': // &gt; SET_HTML_ENTITY("&gt;"); break; default: if (*ucp >= 0x80) { #ifdef UNICODE if (aFlags & TRANS_HTML_NAMED) { switch (*ucp) { case 0x0152: SET_HTML_ENTITY("&OElig;"); goto end_set_entity; case 0x0153: SET_HTML_ENTITY("&oelig;"); goto end_set_entity; case 0x0160: SET_HTML_ENTITY("&Scaron;"); goto end_set_entity; case 0x0161: SET_HTML_ENTITY("&scaron;"); goto end_set_entity; case 0x0178: SET_HTML_ENTITY("&Yuml;"); goto end_set_entity; case 0x0192: SET_HTML_ENTITY("&fnof;"); goto end_set_entity; case 0x02C6: SET_HTML_ENTITY("&circ;"); goto end_set_entity; case 0x02DC: SET_HTML_ENTITY("&tilde;"); goto end_set_entity; case 0x2013: SET_HTML_ENTITY("&ndash;"); goto end_set_entity; case 0x2014: SET_HTML_ENTITY("&mdash;"); goto end_set_entity; case 0x2018: SET_HTML_ENTITY("&lsquo;"); goto end_set_entity; case 0x2019: SET_HTML_ENTITY("&rsquo;"); goto end_set_entity; case 0x201A: SET_HTML_ENTITY("&sbquo;"); goto end_set_entity; case 0x201C: SET_HTML_ENTITY("&ldquo;"); goto end_set_entity; case 0x201D: SET_HTML_ENTITY("&rdquo;"); goto end_set_entity; case 0x201E: SET_HTML_ENTITY("&bdquo;"); goto end_set_entity; case 0x2020: SET_HTML_ENTITY("&dagger;"); goto end_set_entity; case 0x2021: SET_HTML_ENTITY("&Dagger;"); goto end_set_entity; case 0x2022: SET_HTML_ENTITY("&bull;"); goto end_set_entity; case 0x2026: SET_HTML_ENTITY("&hellip;"); goto end_set_entity; case 0x2030: SET_HTML_ENTITY("&permil;"); goto end_set_entity; case 0x2039: SET_HTML_ENTITY("&lsaquo;"); goto end_set_entity; case 0x203A: SET_HTML_ENTITY("&rsaquo;"); goto end_set_entity; case 0x20AC: SET_HTML_ENTITY("&euro;"); goto end_set_entity; case 0x2122: SET_HTML_ENTITY("&trade;"); goto end_set_entity; default: if (*ucp >= 0xA0 && *ucp <= 0xFF) { *contents++ = '&'; _tcscpy(contents, sHtml[*ucp - 0xA0]); contents += _tcslen(contents); *contents++ = ';'; goto end_set_entity; } // else handled by the following break; } // switch (*ucp) } // if (aFlags & TRANS_HTML_NAMED) if (aFlags & TRANS_HTML_NUMBERED) contents += _stprintf(contents, _T("&#%d;"), (int) *ucp); else *contents++ = *ucp; end_set_entity: ; // prevents compilation error #else *contents++ = '&'; // v1.0.40.02 _tcscpy(contents, sHtml[*ucp - 0x80]); contents += _tcslen(contents); // Added as a fix in v1.0.41 (broken in v1.0.40.02). *contents++ = ';'; // v1.0.40.02 #endif } else *contents++ = *ucp; } #undef SET_HTML_ENTITY } *contents = '\0'; // Terminate the string. return output_var.Close(); // Must be called after Assign(NULL, ...) or when Contents() has been altered because it updates the variable's attributes and properly handles VAR_CLIPBOARD. } case TRANS_CMD_MOD: if ( !(value_double2 = ATOF(aValue2)) ) // Divide by zero, set it to be blank to indicate the problem. return output_var.Assign(); // Otherwise: result_double = qmathFmod(ATOF(aValue1), value_double2); ASSIGN_BASED_ON_TYPE case TRANS_CMD_POW: { // v1.0.44.11: With Laszlo's help, negative bases are now supported as long as the exponent is not fractional. // See SYM_POWER in script_expression.cpp for similar code and more comments. value_double1 = ATOF(aValue1); value_double2 = ATOF(aValue2); bool value1_was_negative = (value_double1 < 0); if (value_double1 == 0.0 && value_double2 < 0 // In essence, this is divide-by-zero. || value1_was_negative && qmathFmod(value_double2, 1.0) != 0.0) // Negative base but exponent isn't close enough to being an integer: unsupported (to simplify code). return output_var.Assign(); // Return a consistent result (blank) rather than something that varies. // Otherwise: if (value1_was_negative) value_double1 = -value_double1; // Force a positive due to the limitations of qmathPow(). result_double = qmathPow(value_double1, value_double2); if (value1_was_negative && qmathFabs(qmathFmod(value_double2, 2.0)) == 1.0) // Negative base and exactly-odd exponent (otherwise, it can only be zero or even because if not it would have returned higher above). result_double = -result_double; ASSIGN_BASED_ON_TYPE_POW } case TRANS_CMD_EXP: return output_var.Assign(qmathExp(ATOF(aValue1))); case TRANS_CMD_SQRT: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathSqrt(value_double1)); case TRANS_CMD_LOG: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathLog10(ATOF(aValue1))); case TRANS_CMD_LN: value_double1 = ATOF(aValue1); if (value_double1 < 0) return output_var.Assign(); return output_var.Assign(qmathLog(ATOF(aValue1))); case TRANS_CMD_ROUND: // In the future, a string conversion algorithm might be better to avoid the loss // of 64-bit integer precision that it currently caused by the use of doubles in // the calculation: value32 = ATOI(aValue2); multiplier = *aValue2 ? qmathPow(10, value32) : 1; value_double1 = ATOF(aValue1); result_double = (value_double1 >= 0.0 ? qmathFloor(value_double1 * multiplier + 0.5) : qmathCeil(value_double1 * multiplier - 0.5)) / multiplier; ASSIGN_BASED_ON_TYPE_SINGLE_ROUND case TRANS_CMD_CEIL: case TRANS_CMD_FLOOR: // The code here is similar to that in BIF_FloorCeil(), so maintain them together. result_double = ATOF(aValue1); result_double = (trans_cmd == TRANS_CMD_FLOOR) ? qmathFloor(result_double) : qmathCeil(result_double); return output_var.Assign((__int64)(result_double + (result_double > 0 ? 0.2 : -0.2))); // Fixed for v1.0.40.05: See comments in BIF_FloorCeil() for details. case TRANS_CMD_ABS: { // Seems better to convert as string to avoid loss of 64-bit integer precision // that would be caused by conversion to double. I think this will work even // for negative hex numbers that are close to the 64-bit limit since they too have // a minus sign when generated by the script (e.g. -0x1). //result_double = qmathFabs(ATOF(aValue1)); //ASSIGN_BASED_ON_TYPE_SINGLE LPTSTR cp = omit_leading_whitespace(aValue1); // i.e. caller doesn't have to have ltrimmed it. if (*cp == '-') return output_var.Assign(cp + 1); // Omit the first minus sign (simple conversion only). // Otherwise, no minus sign, so just omit the leading whitespace for consistency: return output_var.Assign(cp); } case TRANS_CMD_SIN: return output_var.Assign(qmathSin(ATOF(aValue1))); case TRANS_CMD_COS: return output_var.Assign(qmathCos(ATOF(aValue1))); case TRANS_CMD_TAN: return output_var.Assign(qmathTan(ATOF(aValue1))); case TRANS_CMD_ASIN: value_double1 = ATOF(aValue1); if (value_double1 > 1 || value_double1 < -1) return output_var.Assign(); // ASin and ACos aren't defined for other values. return output_var.Assign(qmathAsin(ATOF(aValue1))); case TRANS_CMD_ACOS: value_double1 = ATOF(aValue1); if (value_double1 > 1 || value_double1 < -1) return output_var.Assign(); // ASin and ACos aren't defined for other values. return output_var.Assign(qmathAcos(ATOF(aValue1))); case TRANS_CMD_ATAN: return output_var.Assign(qmathAtan(ATOF(aValue1))); // For all of the below bitwise operations: // Seems better to convert to signed rather than unsigned so that signed values can // be supported. i.e. it seems better to trade one bit in capacity in order to support // negative numbers. Another reason is that commands such as IfEquals use ATOI64 (signed), // so if we were to produce unsigned 64 bit values here, they would be somewhat incompatible // with other script operations. case TRANS_CMD_BITAND: return output_var.Assign(ATOI64(aValue1) & ATOI64(aValue2)); case TRANS_CMD_BITOR: return output_var.Assign(ATOI64(aValue1) | ATOI64(aValue2)); case TRANS_CMD_BITXOR: return output_var.Assign(ATOI64(aValue1) ^ ATOI64(aValue2)); case TRANS_CMD_BITNOT: value64 = ATOI64(aValue1); if (value64 < 0 || value64 > UINT_MAX) // Treat it as a 64-bit signed value, since no other aspects of the program // (e.g. IfEqual) will recognize an unsigned 64 bit number. return output_var.Assign(~value64); else // Treat it as a 32-bit unsigned value when inverting and assigning. This is // because assigning it as a signed value would "convert" it into a 64-bit // value, which in turn is caused by the fact that the script sees all negative // numbers as 64-bit values (e.g. -1 is 0xFFFFFFFFFFFFFFFF). return output_var.Assign(~(DWORD)value64); case TRANS_CMD_BITSHIFTLEFT: // Equivalent to multiplying by 2^value2 return output_var.Assign(ATOI64(aValue1) << ATOI(aValue2)); case TRANS_CMD_BITSHIFTRIGHT: // Equivalent to dividing (integer) by 2^value2 return output_var.Assign(ATOI64(aValue1) >> ATOI(aValue2)); } return FAIL; // Never executed (increases maintainability and avoids compiler warning). } #ifndef MINIDLL ResultType Line::Input() // OVERVIEW: // Although a script can have many concurrent quasi-threads, there can only be one input // at a time. Thus, if an input is ongoing and a new thread starts, and it begins its // own input, that input should terminate the prior input prior to beginning the new one. // In a "worst case" scenario, each interrupted quasi-thread could have its own // input, which is in turn terminated by the thread that interrupts it. Every time // this function returns, it must be sure to set g_input.status to INPUT_OFF beforehand. // This signals the quasi-threads beneath, when they finally return, that their input // was terminated due to a new input that took precedence. { if (g_os.IsWin9x()) // v1.0.44.14: For simplicity, do nothing on Win9x rather than try to see if it actually supports the hook (such as if its some kind of emulated/hybrid OS). return OK; // Could also set ErrorLevel to "Timeout" and output_var to be blank, but the benefits to backward compatibility seemed too dubious. // Since other script threads can interrupt this command while it's running, 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. Var *output_var = OUTPUT_VAR; // See comment above. if (!output_var) { // No output variable, which due to load-time validation means there are no other args either. // This means that the user is specifically canceling the prior input (if any). Thus, our // ErrorLevel here is set to 1 or 0, but the prior input's ErrorLevel will be set to "NewInput" // when its quasi-thread is resumed: bool prior_input_is_being_terminated = (g_input.status == INPUT_IN_PROGRESS); g_input.status = INPUT_OFF; return SetErrorLevelOrThrowBool(!prior_input_is_being_terminated); // Above: It's considered an "error" of sorts when there is no prior input to terminate. } // Below are done directly this way rather than passed in as args mainly to emphasize that // ArgLength() can safely be called in Line methods like this one (which is done further below). // It also may also slightly improve performance and reduce code size. LPTSTR aOptions = ARG2, aEndKeys = ARG3, aMatchList = ARG4; // The aEndKeys string must be modifiable (not constant), since for performance reasons, // it's allowed to be temporarily altered by this function. // Set default in case of early return (we want these to be in effect even if // FAIL is returned for our thread, since the underlying thread that had the // active input prior to us didn't fail and it it needs to know how its input // was terminated): g_input.status = INPUT_OFF; ////////////////////////////////////////////// // Set up sparse arrays according to aEndKeys: ////////////////////////////////////////////// UCHAR end_vk[VK_ARRAY_COUNT] = {0}; // A sparse array that indicates which VKs terminate the input. UCHAR end_sc[SC_ARRAY_COUNT] = {0}; // A sparse array that indicates which SCs terminate the input. vk_type vk; sc_type sc = 0; modLR_type modifiersLR; size_t key_text_length; TCHAR *end_pos, single_char_string[2]; single_char_string[1] = '\0'; // Init its second character once, since the loop only changes the first char. for (; *aEndKeys; ++aEndKeys) // 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 (*aEndKeys) { case '}': continue; // Important that these be ignored. case '{': { if ( !(end_pos = _tcschr(aEndKeys + 1, '}')) ) continue; // Do nothing, just ignore the unclosed '{' and continue. if ( !(key_text_length = end_pos - aEndKeys - 1) ) { 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. } *end_pos = '\0'; // temporarily terminate the string here. // v1.0.45: Fixed this section to differentiate between } and ] (and also { and [, as well as // anything else enclosed in {} that requires END_KEY_WITH_SHIFT/END_KEY_WITHOUT_SHIFT consideration. modifiersLR = 0; // Init prior to below. if (vk = TextToVK(aEndKeys + 1, &modifiersLR, true)) { if (key_text_length == 1) *single_char_string = aEndKeys[1]; //else leave it at its default of "not a single-char key-name". } else // No virtual key, so try to find a scan code. if (sc = TextToSC(aEndKeys + 1)) end_sc[sc] = END_KEY_ENABLED; *end_pos = '}'; // undo the temporary termination aEndKeys = end_pos; // In prep for aEndKeys++ at the bottom of the loop. break; // Break out of the switch() and do the vk handling beneath it (if there is a vk). } default: *single_char_string = *aEndKeys; modifiersLR = 0; // Init prior to below. vk = TextToVK(single_char_string, &modifiersLR, true); } // switch() if (vk) // A valid virtual key code was discovered above. { end_vk[vk] |= END_KEY_ENABLED; // Use of |= is essential for cases such as ";:". // Insist the shift key be down to form genuinely different symbols -- // namely punctuation marks -- but not for alphabetic chars. In the // future, an option can be added to the Options param to treat // end chars as case sensitive (if there is any demand for that): if (*single_char_string && !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; } } } // for() ///////////////////////////////////////////////// // Parse aMatchList into an array of key phrases: ///////////////////////////////////////////////// LPTSTR *realloc_temp; // Needed since realloc returns NULL on failure but leaves original block allocated. g_input.MatchCount = 0; // Set default. if (*aMatchList) { // If needed, create the array of pointers that points into MatchBuf to each match phrase: if (!g_input.match) { if ( !(g_input.match = (LPTSTR *)malloc(INPUT_ARRAY_BLOCK_SIZE * sizeof(LPTSTR))) ) return LineError(ERR_OUTOFMEM); // Short msg. since so rare. g_input.MatchCountMax = INPUT_ARRAY_BLOCK_SIZE; } // If needed, create or enlarge the buffer that contains all the match phrases: size_t aMatchList_length = ArgLength(4); // Performs better than _tcslen(aMatchList); size_t space_needed = aMatchList_length + 1; // +1 for the final zero terminator. if (space_needed > g_input.MatchBufSize) { g_input.MatchBufSize = (UINT)(space_needed > 4096 ? space_needed : 4096); if (g_input.MatchBuf) // free the old one since it's too small. free(g_input.MatchBuf); if ( !(g_input.MatchBuf = tmalloc(g_input.MatchBufSize)) ) { g_input.MatchBufSize = 0; return LineError(ERR_OUTOFMEM); // Short msg. since so rare. } } // Copy aMatchList into the match buffer: LPTSTR source, dest; for (source = aMatchList, dest = g_input.match[g_input.MatchCount] = g_input.MatchBuf ; *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 (*g_input.match[g_input.MatchCount]) { ++g_input.MatchCount; g_input.match[g_input.MatchCount] = ++dest; *dest = '\0'; // Init to prevent crash on orphaned comma such as "btw,otoh," } if (*(source + 1)) // There is a next element. { if (g_input.MatchCount >= g_input.MatchCountMax) // Rarely needed, so just realloc() to expand. { // Expand the array by one block: if ( !(realloc_temp = (LPTSTR *)realloc(g_input.match // Must use a temp variable. , (g_input.MatchCountMax + INPUT_ARRAY_BLOCK_SIZE) * sizeof(LPTSTR))) ) return LineError(ERR_OUTOFMEM); // Short msg. since so rare. g_input.match = realloc_temp; g_input.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 (*g_input.match[g_input.MatchCount]) // i.e. omit empty strings from the match list. ++g_input.MatchCount; } // Notes about the below macro: // In case the Input timer has already put a WM_TIMER msg in our queue before we killed it, // clean out the queue now to avoid any chance that such a WM_TIMER message will take effect // later when it would be unexpected and might interfere with this input. To avoid an // unnecessary call to PeekMessage(), which has been known to yield our timeslice to other // processes if the CPU is under load (which might be undesirable if this input is // time-critical, such as in a game), call GetQueueStatus() to see if there are any timer // messages in the queue. I believe that GetQueueStatus(), unlike PeekMessage(), does not // have the nasty/undocumented side-effect of yielding our timeslice under certain hard-to-reproduce // circumstances, but Google and MSDN are completely devoid of any confirming info on this. #define KILL_AND_PURGE_INPUT_TIMER \ if (g_InputTimerExists)\ {\ KILL_INPUT_TIMER \ if (HIWORD(GetQueueStatus(QS_TIMER)) & QS_TIMER)\ MsgSleep(-1);\ } // Be sure to get rid of the timer if it exists due to a prior, ongoing input. // It seems best to do this only after signaling the hook to start the input // so that it's MsgSleep(-1), if it launches a new hotkey or timed subroutine, // will be less likely to interrupt us during our setup of the input, i.e. // it seems best that we put the input in progress prior to allowing any // interruption. UPDATE: Must do this before changing to INPUT_IN_PROGRESS // because otherwise the purging of the timer message might call InputTimeout(), // which in turn would set the status immediately to INPUT_TIMED_OUT: KILL_AND_PURGE_INPUT_TIMER ////////////////////////////////////////////////////////////// // Initialize buffers and state variables for use by the hook: ////////////////////////////////////////////////////////////// // Set the defaults that will be in effect unless overridden by an item in aOptions: g_input.BackspaceIsUndo = true; g_input.CaseSensitive = false; g_input.IgnoreAHKInput = false; g_input.TranscribeModifiedKeys = false; g_input.Visible = false; g_input.FindAnywhere = false; int timeout = 0; // Set default. TCHAR input_buf[INPUT_BUFFER_SIZE] = _T(""); // Will contain the actual input from the user. + TCHAR prev_buf[INPUT_BUFFER_SIZE] = _T(""); g_input.buffer = input_buf; g_input.BufferLength = 0; g_input.BufferLengthMax = INPUT_BUFFER_SIZE - 1; for (LPTSTR cp = aOptions; *cp; ++cp) { switch(ctoupper(*cp)) { case 'A': - _tcscpy(g_input.buffer,output_var->Contents()); - g_input.BufferLength = (int)_tcslen(g_input.buffer); + if (_tcslen(output_var->Contents())) // Append value if variable is not empty (only strings allowed) + { + g_input.BufferLength = (int) _tcslen(output_var->Contents()); + if (g_input.BufferLength > INPUT_BUFFER_SIZE - 1) + g_input.BufferLength = INPUT_BUFFER_SIZE - 1; + _tcsncpy(input_buf,output_var->Contents(),g_input.BufferLength); + _tcscpy(prev_buf,input_buf); + } break; case 'B': g_input.BackspaceIsUndo = false; break; case 'C': g_input.CaseSensitive = true; break; case 'I': g_input.IgnoreAHKInput = true; break; case 'M': g_input.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: g_input.BufferLengthMax = _ttoi(cp + 1); if (g_input.BufferLengthMax > INPUT_BUFFER_SIZE - 1) g_input.BufferLengthMax = INPUT_BUFFER_SIZE - 1; 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': g_input.Visible = true; break; case '*': g_input.FindAnywhere = true; break; } } // Point the global addresses to our memory areas on the stack: g_input.EndVK = end_vk; g_input.EndSC = end_sc; g_input.status = INPUT_IN_PROGRESS; // Signal the hook to start the input. // Make script persistent. This is mostly for backward compatibility because it is documented behavior. // even though as of v1.0.42.03, the keyboard hook does not become permanent (which allows a subsequent // use of the commands Suspend/Hotkey to deinstall it, which seems to add flexibility/benefit). g_persistent = true; Hotkey::InstallKeybdHook(); // Install the hook (if needed). // A timer is used rather than monitoring the elapsed time here directly because // this script's quasi-thread might be interrupted by a Timer or Hotkey subroutine, // which (if it takes a long time) would result in our Input not obeying its timeout. // By using an actual timer, the TimerProc() will run when the timer expires regardless // of which quasi-thread is active, and it will end our input on schedule: if (timeout > 0) SET_INPUT_TIMER(timeout < 10 ? 10 : timeout) ////////////////////////////////////////////////////////////////// // Wait for one of the following to terminate our input: // 1) The hook (due a match in aEndKeys or aMatchList); // 2) A thread that interrupts us with a new Input of its own; // 3) The timer we put in effect for our timeout (if we have one). ////////////////////////////////////////////////////////////////// - // HotKeyIt H24 check for vars contents and updatebuffer - TCHAR prev_buf[INPUT_BUFFER_SIZE]; - if ((int)output_var->Length() <= INPUT_BUFFER_SIZE) - _tcscpy(prev_buf,output_var->Contents()); + for (;;) { // Rather than monitoring the timeout here, just wait for the incoming WM_TIMER message // to take effect as a TimerProc() call during the MsgSleep(): MsgSleep(); - // HotKeyIt H15 added for multithreading support so variable can be read from other threads while input is in progress - if (_tcscmp(prev_buf,output_var->Contents())) // HotKeyIt H24 check for vars contents and updatebuffer + // HotKeyIt added multi-threading support so variable can be read from other threads while input is in progress + if (_tcsncmp(prev_buf,output_var->Contents(),_tcslen(output_var->Contents()) > INPUT_BUFFER_SIZE - 1 ? INPUT_BUFFER_SIZE - 1 : _tcslen(output_var->Contents()))) // Check for vars contents and updatebuffer { - if ((int)output_var->Length() <= INPUT_BUFFER_SIZE) - { - g_input.BufferLength = (int)output_var->Length(); - _tcscpy(g_input.buffer,output_var->Contents()); - _tcscpy(prev_buf,output_var->Contents()); - } + g_input.BufferLength = (int) _tcslen(output_var->Contents()); + if (g_input.BufferLength > INPUT_BUFFER_SIZE - 1) + g_input.BufferLength = INPUT_BUFFER_SIZE - 1; + _tcsncpy(input_buf,output_var->Contents(),g_input.BufferLength); + _tcscpy(prev_buf,input_buf); } else if (_tcscmp(prev_buf,input_buf)) { - output_var->Assign(input_buf); - _tcscpy(prev_buf,output_var->Contents()); + if (_tcslen(input_buf) || !output_var->CharCapacity()) // Assign will free memory if input_buf empty + { + output_var->Assign(input_buf); + _tcscpy(prev_buf,input_buf); + } + else + { // Assign empty string + *output_var->mAliasFor->mCharContents = '\0'; + *prev_buf = '\0'; + } } if (g_input.status != INPUT_IN_PROGRESS) break; } switch(g_input.status) { case INPUT_TIMED_OUT: g_ErrorLevel->Assign(_T("Timeout")); break; case INPUT_TERMINATED_BY_MATCH: g_ErrorLevel->Assign(_T("Match")); break; case INPUT_TERMINATED_BY_ENDKEY: { TCHAR key_name[128] = _T("EndKey:"); if (g_input.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(g_input.EndingVK, vk_to_sc(g_input.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 + 7, 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 + 7 + count) = '\0'; // Terminate the string. } else g_input.EndedBySC ? SCtoKeyName(g_input.EndingSC, key_name + 7, _countof(key_name) - 7) : VKtoKeyName(g_input.EndingVK, key_name + 7, _countof(key_name) - 7); g_ErrorLevel->Assign(key_name); break; } case INPUT_LIMIT_REACHED: g_ErrorLevel->Assign(_T("Max")); break; default: // Our input was terminated due to a new input in a quasi-thread that interrupted ours. g_ErrorLevel->Assign(_T("NewInput")); break; } g_input.status = INPUT_OFF; // See OVERVIEW above for why this must be set prior to returning. // In case it ended for reason other than a timeout, in which case the timer is still on: KILL_AND_PURGE_INPUT_TIMER // Seems ok to assign after the kill/purge above since input_buf is our own stack variable // and its contents shouldn't be affected even if KILL_AND_PURGE_INPUT_TIMER's MsgSleep() // results in a new thread being created that starts a new Input: - return output_var->Assign(input_buf); + if (_tcslen(input_buf) || !output_var->CharCapacity()) // Assign will free memory if input_buf empty + return output_var->Assign(input_buf); + else + { + *output_var->mAliasFor->mCharContents = '\0'; // Assign empty string + return OK; + } } #endif ResultType Line::PerformShowWindow(ActionTypeType aActionType, LPTSTR aTitle, LPTSTR aText , LPTSTR aExcludeTitle, LPTSTR aExcludeText) { // 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 = (aActionType == ACT_WINSHOW && !g->DetectHiddenWindows); if (need_restore) g->DetectHiddenWindows = true; HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (need_restore) g->DetectHiddenWindows = false; if (!target_window) return OK; // WinGroup's EnumParentActUponAll() is quite similar to the following, so the two should be // maintained together. int nCmdShow = SW_NONE; // Set default. switch (aActionType) { // 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 ACT_WINMINIMIZE: if (IsWindowHung(target_window)) { if (g_os.IsWin2000orLater()) nCmdShow = SW_FORCEMINIMIZE; //else it's not Win2k or later. I have confirmed that 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 ACT_WINMAXIMIZE: if (!IsWindowHung(target_window)) nCmdShow = SW_MAXIMIZE; break; case ACT_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 ACT_WINHIDE: nCmdShow = SW_HIDE; break; case ACT_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); //PostMessage(target_window, WM_SYSCOMMAND, SC_MINIMIZE, 0); DoWinDelay; } return OK; // Return success for all the above cases. } ResultType Line::PerformWait() // Since other script threads can interrupt these commands while they're running, it's important that // these commands 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. // fincs: it seems best that this function not throw an exception if the wait timeouts. { bool wait_indefinitely; int sleep_duration; DWORD start_time; vk_type vk; // For GetKeyState. HANDLE running_process; // For RUNWAIT DWORD exit_code; // For RUNWAIT // For ACT_KEYWAIT: bool wait_for_keydown; KeyStateTypes key_state_type; JoyControls joy; int joystick_id; ExprTokenType token; TCHAR buf[LINE_SIZE]; if (mActionType == ACT_RUNWAIT) { bool use_el = tcscasestr(ARG3, _T("UseErrorLevel")); if (!g_script.ActionExec(ARG1, NULL, ARG2, !use_el, ARG3, &running_process, use_el, true, ARGVAR4)) // Load-time validation has ensured that the arg is a valid output variable (e.g. not a built-in var). return use_el ? g_ErrorLevel->Assign(_T("ERROR")) : FAIL; //else fall through to the waiting-phase of the operation. // Above: The special string ERROR is used, rather than a number like 1, because currently // RunWait might in the future be able to return any value, including 259 (STATUS_PENDING). } // Must NOT use ELSE-IF in line below due to ELSE further down needing to execute for RunWait. if (mActionType == ACT_KEYWAIT) { if ( !(vk = TextToVK(ARG1)) ) { if ( !(joy = (JoyControls)ConvertJoy(ARG1, &joystick_id)) ) // Not a valid key name. // Indicate immediate timeout (if timeout was specified) or error. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); if (!IS_JOYSTICK_BUTTON(joy)) // Currently, only buttons are supported. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); } // Set defaults: wait_for_keydown = false; // The default is to wait for the key to be released. key_state_type = KEYSTATE_PHYSICAL; // Since physical is more often used. wait_indefinitely = true; sleep_duration = 0; for (LPTSTR cp = ARG2; *cp; ++cp) { switch(ctoupper(*cp)) { case 'D': wait_for_keydown = true; break; case 'L': key_state_type = KEYSTATE_LOGICAL; 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: wait_indefinitely = false; sleep_duration = (int)(ATOF(cp + 1) * 1000); break; } } // The following must be set for ScriptGetJoyState(): token.symbol = SYM_STRING; token.marker = buf; } else if ( (mActionType != ACT_RUNWAIT && mActionType != ACT_CLIPWAIT && *ARG3) || (mActionType == ACT_CLIPWAIT && *ARG1) ) { // Since the param containing the timeout value isn't blank, it must be numeric, // otherwise, the loading validation would have prevented the script from loading. wait_indefinitely = false; sleep_duration = (int)(ATOF(mActionType == ACT_CLIPWAIT ? ARG1 : ARG3) * 1000); // Can be zero. if (sleep_duration < 1) // Waiting 500ms in place of a "0" seems more useful than a true zero, which // doens't need to be supported because it's the same thing as something like // "IfWinExist". A true zero for clipboard would be the same as // "IfEqual, clipboard, , xxx" (though admittedly it's higher overhead to // actually fetch the contents of the clipboard). sleep_duration = 500; } else { wait_indefinitely = true; sleep_duration = 0; // Just to catch any bugs. } if (mActionType != ACT_RUNWAIT) g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Set default ErrorLevel to be possibly overridden later on. bool any_clipboard_format = (mActionType == ACT_CLIPWAIT && ArgToInt(2) == 1); // Right before starting the wait-loop, make a copy of our args using the stack // space in our recursion layer. This is done in case other hotkey subroutine(s) // are launched while we're waiting here, which might cause our args to be overwritten // if any of them happen to be in the Deref buffer: LPTSTR arg[MAX_ARGS], marker; int i, space_remaining; for (i = 0, space_remaining = LINE_SIZE, marker = buf; i < mArgc; ++i) { if (!space_remaining) // Realistically, should never happen. arg[i] = _T(""); else { arg[i] = marker; // Point it to its place in the buffer. tcslcpy(marker, sArgDeref[i], space_remaining); // Make the copy. marker += _tcslen(marker) + 1; // +1 for the zero terminator of each arg. space_remaining = (int)(LINE_SIZE - (marker - buf)); } } for (start_time = GetTickCount();;) // start_time is initialized unconditionally for use with v1.0.30.02's new logging feature further below. { // Always do the first iteration so that at least one check is done. switch(mActionType) { case ACT_WINWAIT: #define SAVED_WIN_ARGS SAVED_ARG1, SAVED_ARG2, SAVED_ARG4, SAVED_ARG5 if (WinExist(*g, SAVED_WIN_ARGS, false, true)) { DoWinDelay; return OK; } break; case ACT_WINWAITCLOSE: if (!WinExist(*g, SAVED_WIN_ARGS)) { DoWinDelay; return OK; } break; case ACT_WINWAITACTIVE: if (WinActive(*g, SAVED_WIN_ARGS, true)) { DoWinDelay; return OK; } break; case ACT_WINWAITNOTACTIVE: if (!WinActive(*g, SAVED_WIN_ARGS, true)) { DoWinDelay; return OK; } break; case ACT_CLIPWAIT: // Seems best to consider CF_HDROP to be a non-empty clipboard, since we // support the implicit conversion of that format to text: if (any_clipboard_format) { if (CountClipboardFormats()) return OK; } else if (IsClipboardFormatAvailable(CF_NATIVETEXT) || IsClipboardFormatAvailable(CF_HDROP)) return OK; break; case ACT_KEYWAIT: if (vk) // Waiting for key or mouse button, not joystick. { if (ScriptGetKeyState(vk, key_state_type) == wait_for_keydown) return OK; } else // Waiting for joystick button { if ((bool)ScriptGetJoyState(joy, joystick_id, token, false) == wait_for_keydown) return OK; } break; case ACT_RUNWAIT: // Pretty nasty, but for now, nothing is done to prevent an infinite loop. // In the future, maybe OpenProcess() can be used to detect if a process still // exists (is there any other way?): // MSDN: "Warning: If a process happens to return STILL_ACTIVE (259) as an error code, // applications that test for this value could end up in an infinite loop." if (running_process) GetExitCodeProcess(running_process, &exit_code); else // it can be NULL in the case of launching things like "find D:\" or "www.yahoo.com" exit_code = 0; if (exit_code != STATUS_PENDING) // STATUS_PENDING == STILL_ACTIVE { if (running_process) 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: return g_ErrorLevel->Assign((int)exit_code); } break; } // Must cast to int or any negative result will be lost due to DWORD type: if (wait_indefinitely || (int)(sleep_duration - (GetTickCount() - start_time)) > SLEEP_INTERVAL_HALF) { if (MsgSleep(INTERVAL_UNSPECIFIED)) // INTERVAL_UNSPECIFIED performs better. { // 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) { sLog[sLogNext] = this; sLogTick[sLogNext++] = start_time; // Store a special value so that Line::LogToText() can report that its "still waiting" from earlier. if (sLogNext >= LINE_LOG_SIZE) sLogNext = 0; // The lines above are the similar to those used in ExecUntil(), so the two should be // maintained together. } } } else // Done waiting. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Since it timed out, we override the default with this. } // for() } ResultType Line::WinMove(LPTSTR aTitle, LPTSTR aText, LPTSTR aX, LPTSTR aY , LPTSTR aWidth, LPTSTR aHeight, LPTSTR aExcludeTitle, LPTSTR aExcludeText) { // So that compatibility is retained, don't set ErrorLevel for commands that are native to AutoIt2 // but that AutoIt2 doesn't use ErrorLevel with (such as this one). HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) return OK; RECT rect; if (!GetWindowRect(target_window, &rect)) return OK; // Can't set errorlevel, see above. MoveWindow(target_window , *aX && _tcsicmp(aX, _T("default")) ? ATOI(aX) : rect.left // X-position , *aY && _tcsicmp(aY, _T("default")) ? ATOI(aY) : rect.top // Y-position , *aWidth && _tcsicmp(aWidth, _T("default")) ? ATOI(aWidth) : rect.right - rect.left , *aHeight && _tcsicmp(aHeight, _T("default")) ? ATOI(aHeight) : rect.bottom - rect.top , TRUE); // Do repaint. DoWinDelay; return OK; } ResultType Line::ControlSend(LPTSTR aControl, LPTSTR aKeysToSend, LPTSTR aTitle, LPTSTR aText , LPTSTR aExcludeTitle, LPTSTR aExcludeText, bool aSendRaw) { HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) goto error; HWND control_window = _tcsicmp(aControl, _T("ahk_parent")) ? ControlExist(target_window, aControl) // This can return target_window itself for cases such as ahk_id %ControlHWND%. : target_window; if (!control_window) goto error; SendKeys(aKeysToSend, aSendRaw, SM_EVENT, control_window); // But don't do WinDelay because KeyDelay should have been in effect for the above. return g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Indicate success. error: return SetErrorLevelOrThrow(); } ResultType Line::ControlClick(vk_type aVK, int aClickCount, LPTSTR aOptions, LPTSTR aControl , LPTSTR aTitle, LPTSTR aText, LPTSTR aExcludeTitle, LPTSTR aExcludeText) { HWND target_window = DetermineTargetWindow(aTitle, aText, aExcludeTitle, aExcludeText); if (!target_window) goto error; // 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 (LPTSTR cp = aOptions; *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; } } // 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. HWND control_window = position_mode ? NULL : ControlExist(target_window, aControl); // This can return target_window itself for cases such as ahk_id %ControlHWND%. if (!control_window) // 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}; // Parse the X an Y coordinates in a strict way to reduce ambiguity with control names and also // to keep the code simple. LPTSTR cp = omit_leading_whitespace(aControl); if (ctoupper(*cp) != 'X') goto error; ++cp; if (!*cp) goto 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 error; cp = omit_leading_whitespace(cp + 1); if (!*cp || _totupper(*cp) != 'Y') goto error; ++cp; if (!*cp) goto error; pah.pt.y = ATOI(cp); // The passed-in coordinates are always relative to target_window's upper left corner because offering // an option for absolute/screen coordinates doesn't seem useful. RECT rect; GetWindowRect(target_window, &rect); pah.pt.x += rect.left; // Convert to screen coordinates. pah.pt.y += rect.top; 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 set an ErrorLevel of 1 (above) whenever the // target window or control isn't found, or any other error condition occurs above: if (aClickCount < 1) // 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 g_ErrorLevel->Assign(ERRORLEVEL_NONE); 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)) goto error; if (click.x == COORD_UNSPECIFIED) click.x = (rect.right - rect.left) / 2; if (click.y == COORD_UNSPECIFIED) click.y = (rect.bottom - rect.top) / 2; } LPARAM lparam = MAKELPARAM(click.x, click.y); UINT msg_down, msg_up; WPARAM wparam; 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) { wparam = (aClickCount * ((aVK == VK_WHEEL_UP) ? WHEEL_DELTA : -WHEEL_DELTA)) << 16; // High order word contains the 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
tinku99/ahkdll
7b0fbc19b4d18f6d2bcbd9492408d614e5c822a6
modified: source/defines.h ListLines off for sandbox
diff --git a/source/defines.h b/source/defines.h index 58d92e3..2c44988 100644 --- a/source/defines.h +++ b/source/defines.h @@ -287,555 +287,555 @@ enum enum_act { , ACT_IFLESS, ACT_IFLESSOREQUAL , ACT_FIRST_OPTIMIZED_IF = ACT_IFBETWEEN, ACT_LAST_OPTIMIZED_IF = ACT_IFLESSOREQUAL , ACT_FIRST_COMMAND // i.e the above aren't considered commands for parsing/searching purposes. , ACT_IFWINEXIST = ACT_FIRST_COMMAND , ACT_IFWINNOTEXIST, ACT_IFWINACTIVE, ACT_IFWINNOTACTIVE , ACT_IFINSTRING, ACT_IFNOTINSTRING , ACT_IFEXIST, ACT_IFNOTEXIST, ACT_IFMSGBOX , ACT_FIRST_IF = ACT_IFIN, ACT_LAST_IF = ACT_IFMSGBOX // Keep this range updated with any new IFs that are added. , ACT_MSGBOX, ACT_INPUTBOX, ACT_SPLASHTEXTON, ACT_SPLASHTEXTOFF, ACT_PROGRESS, ACT_SPLASHIMAGE , ACT_TOOLTIP, ACT_TRAYTIP, ACT_INPUT , ACT_TRANSFORM, ACT_STRINGLEFT, ACT_STRINGRIGHT, ACT_STRINGMID , ACT_STRINGTRIMLEFT, ACT_STRINGTRIMRIGHT, ACT_STRINGLOWER, ACT_STRINGUPPER , ACT_STRINGLEN, ACT_STRINGGETPOS, ACT_STRINGREPLACE, ACT_STRINGSPLIT, ACT_SPLITPATH, ACT_SORT , ACT_ENVGET, ACT_ENVSET, ACT_ENVUPDATE , ACT_RUNAS, ACT_RUN, ACT_RUNWAIT, ACT_URLDOWNLOADTOFILE , ACT_GETKEYSTATE , ACT_SEND, ACT_SENDRAW, ACT_SENDINPUT, ACT_SENDPLAY, ACT_SENDEVENT , ACT_CONTROLSEND, ACT_CONTROLSENDRAW, ACT_CONTROLCLICK, ACT_CONTROLMOVE, ACT_CONTROLGETPOS, ACT_CONTROLFOCUS , ACT_CONTROLGETFOCUS, ACT_CONTROLSETTEXT, ACT_CONTROLGETTEXT, ACT_CONTROL, ACT_CONTROLGET , ACT_SENDMODE, ACT_SENDLEVEL, ACT_COORDMODE, ACT_SETDEFAULTMOUSESPEED , ACT_CLICK, ACT_MOUSEMOVE, ACT_MOUSECLICK, ACT_MOUSECLICKDRAG, ACT_MOUSEGETPOS , ACT_STATUSBARGETTEXT , ACT_STATUSBARWAIT , ACT_CLIPWAIT, ACT_KEYWAIT , ACT_SLEEP, ACT_RANDOM , ACT_GOTO, ACT_GOSUB, ACT_ONEXIT, ACT_HOTKEY, ACT_SETTIMER, ACT_CRITICAL, ACT_THREAD, ACT_RETURN, ACT_EXIT , ACT_LOOP, ACT_FOR, ACT_WHILE, ACT_UNTIL, ACT_BREAK, ACT_CONTINUE // Keep LOOP, FOR, WHILE and UNTIL together and in this order for range checks in various places. , ACT_TRY, ACT_CATCH, ACT_THROW , ACT_BLOCK_BEGIN, ACT_BLOCK_END , ACT_WINACTIVATE, ACT_WINACTIVATEBOTTOM , ACT_WINWAIT, ACT_WINWAITCLOSE, ACT_WINWAITACTIVE, ACT_WINWAITNOTACTIVE , ACT_WINMINIMIZE, ACT_WINMAXIMIZE, ACT_WINRESTORE , ACT_WINHIDE, ACT_WINSHOW , ACT_WINMINIMIZEALL, ACT_WINMINIMIZEALLUNDO , ACT_WINCLOSE, ACT_WINKILL, ACT_WINMOVE, ACT_WINMENUSELECTITEM, ACT_PROCESS , ACT_WINSET, ACT_WINSETTITLE, ACT_WINGETTITLE, ACT_WINGETCLASS, ACT_WINGET, ACT_WINGETPOS, ACT_WINGETTEXT , ACT_SYSGET, ACT_POSTMESSAGE, ACT_SENDMESSAGE // Keep rarely used actions near the bottom for parsing/performance reasons: , ACT_PIXELGETCOLOR, ACT_PIXELSEARCH, ACT_IMAGESEARCH , ACT_GROUPADD, ACT_GROUPACTIVATE, ACT_GROUPDEACTIVATE, ACT_GROUPCLOSE , ACT_DRIVESPACEFREE, ACT_DRIVE, ACT_DRIVEGET , ACT_SOUNDGET, ACT_SOUNDSET, ACT_SOUNDGETWAVEVOLUME, ACT_SOUNDSETWAVEVOLUME, ACT_SOUNDBEEP, ACT_SOUNDPLAY , ACT_FILEAPPEND, ACT_FILEREAD, ACT_FILEREADLINE, ACT_FILEDELETE, ACT_FILERECYCLE, ACT_FILERECYCLEEMPTY , ACT_FILEINSTALL, ACT_FILECOPY, ACT_FILEMOVE, ACT_FILECOPYDIR, ACT_FILEMOVEDIR , ACT_FILECREATEDIR, ACT_FILEREMOVEDIR , ACT_FILEGETATTRIB, ACT_FILESETATTRIB, ACT_FILEGETTIME, ACT_FILESETTIME , ACT_FILEGETSIZE, ACT_FILEGETVERSION , ACT_SETWORKINGDIR, ACT_FILESELECTFILE, ACT_FILESELECTFOLDER, ACT_FILEGETSHORTCUT, ACT_FILECREATESHORTCUT , ACT_INIREAD, ACT_INIWRITE, ACT_INIDELETE , ACT_REGREAD, ACT_REGWRITE, ACT_REGDELETE, ACT_OUTPUTDEBUG , ACT_SETKEYDELAY, ACT_SETMOUSEDELAY, ACT_SETWINDELAY, ACT_SETCONTROLDELAY, ACT_SETBATCHLINES , ACT_SETTITLEMATCHMODE, ACT_SETFORMAT, ACT_FORMATTIME , ACT_SUSPEND, ACT_PAUSE , ACT_AUTOTRIM, ACT_STRINGCASESENSE, ACT_DETECTHIDDENWINDOWS, ACT_DETECTHIDDENTEXT, ACT_BLOCKINPUT , ACT_SETNUMLOCKSTATE, ACT_SETSCROLLLOCKSTATE, ACT_SETCAPSLOCKSTATE, ACT_SETSTORECAPSLOCKMODE , ACT_KEYHISTORY, ACT_LISTLINES, ACT_LISTVARS, ACT_LISTHOTKEYS , ACT_EDIT, ACT_RELOAD, ACT_MENU, ACT_GUI, ACT_GUICONTROL, ACT_GUICONTROLGET , ACT_EXITAPP , ACT_SHUTDOWN , ACT_FILEENCODING // Make these the last ones before the count so they will be less often processed. This helps // performance because this one doesn't actually have a keyword so will never result // in a match anyway. UPDATE: No longer used because Run/RunWait is now required, which greatly // improves syntax checking during load: //, ACT_EXEC // It's safer to use g_ActionCount, which is calculated immediately after the array is declared // and initialized, at which time we know its true size. However, the following lets us detect // when the size of the array doesn't match the enum (in debug mode): #ifdef _DEBUG , ACT_COUNT #endif }; enum enum_act_old { OLD_INVALID = FAIL // These should both be zero for initialization and function-return-value purposes. , OLD_SETENV, OLD_ENVADD, OLD_ENVSUB, OLD_ENVMULT, OLD_ENVDIV // ACT_IS_IF_OLD() relies on the items in this next line being adjacent to one another and in this order: , OLD_IFEQUAL, OLD_IFNOTEQUAL, OLD_IFGREATER, OLD_IFGREATEROREQUAL, OLD_IFLESS, OLD_IFLESSOREQUAL , OLD_LEFTCLICK, OLD_RIGHTCLICK, OLD_LEFTCLICKDRAG, OLD_RIGHTCLICKDRAG , OLD_HIDEAUTOITWIN, OLD_REPEAT, OLD_ENDREPEAT , OLD_WINGETACTIVETITLE, OLD_WINGETACTIVESTATS }; // It seems best not to include ACT_SUSPEND in the below, since the user may have marked // a large number of subroutines as "Suspend, Permit". Even PAUSE is iffy, since the user // may be using it as "Pause, off/toggle", but it seems best to support PAUSE because otherwise // hotkey such as "#z::pause" would not be able to unpause the script if its MaxThreadsPerHotkey // was 1 (the default). #ifndef MINIDLL #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_EDIT || ActionType == ACT_RELOAD || ActionType == ACT_KEYHISTORY \ || ActionType == ACT_LISTLINES || ActionType == ACT_LISTVARS || ActionType == ACT_LISTHOTKEYS) #else #define ACT_IS_ALWAYS_ALLOWED(ActionType) (ActionType == ACT_EXITAPP || ActionType == ACT_PAUSE \ || ActionType == ACT_RELOAD) #endif #define ACT_IS_ASSIGN(ActionType) (ActionType <= ACT_ASSIGN_LAST && ActionType >= ACT_ASSIGN_FIRST) // Ordered for short-circuit performance. #define ACT_IS_IF(ActionType) (ActionType >= ACT_FIRST_IF && ActionType <= ACT_LAST_IF) #define ACT_IS_IF_OR_ELSE_OR_LOOP(ActionType) (ACT_IS_IF(ActionType) || ActionType == ACT_ELSE \ || ActionType == ACT_LOOP || ActionType == ACT_WHILE || ActionType == ACT_FOR) #define ACT_IS_IF_OLD(ActionType, OldActionType) (ActionType >= ACT_FIRST_IF_ALLOWING_SAME_LINE_ACTION && ActionType <= ACT_LAST_IF) \ && (ActionType < ACT_IFEQUAL || ActionType > ACT_IFLESSOREQUAL || (OldActionType >= OLD_IFEQUAL && OldActionType <= OLD_IFLESSOREQUAL)) // All the checks above must be done so that cmds such as IfMsgBox (which are both "old" and "new") // can support parameters on the same line or on the next line. For example, both of the above are allowed: // IfMsgBox, No, Gosub, XXX // IfMsgBox, No // Gosub, XXX // 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 // 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. #ifndef MINIDLL #define MAX_INPUTBOXES 4 #define MAX_PROGRESS_WINDOWS 10 // Allow a lot for downloads and such. #define MAX_PROGRESS_WINDOWS_STR _T("10") // Keep this in sync with above. #define MAX_SPLASHIMAGE_WINDOWS 10 #define MAX_SPLASHIMAGE_WINDOWS_STR _T("10") // Keep this in sync with above. #endif #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. #ifndef MINIDLL #define NO_CONTROL_INDEX MAX_CONTROLS_PER_GUI // Must be 0xFFFF or less. #endif #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. #ifndef MINIDLL #define MAX_FILEDIALOGS 4 #define MAX_FOLDERDIALOGS 4 #endif #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. #ifndef MINIDLL // 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 #endif #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 CLOSE_CLIPBOARD_IF_OPEN if (g_clip.mIsOpen) g_clip.Close() #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; // Just make them int's, rather than something smaller, because the collection // of actions will take up very little memory. Int's are probably faster // for the processor to access since they are the native word size, or something: // Update for v1.0.40.02: Now that the ARGn macros don't check mArgc, MaxParamsAu2WithHighBit // is needed to allow MaxParams to stay pure, which in turn prevents Line::Perform() // from accessing a NULL arg in the sArgDeref array (i.e. an arg that exists only for // non-AutoIt2 scripts, such as the extra ones in StringGetPos). // Also, changing these from ints to chars greatly reduces 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, MaxParamsAu2WithHighBit; // Array indicating which args must be purely numeric. The first arg is // number 1, the second 2, etc (i.e. it doesn't start at zero). The list // is ended with a zero, much like a string. The compiler will notify us // (verified) if MAX_NUMERIC_PARAMS ever needs to be increased: #define MAX_NUMERIC_PARAMS 7 ActionTypeType NumericParams[MAX_NUMERIC_PARAMS]; }; #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}; #ifndef MINIDLL 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("Normal"), _T("DoubleClick"), _T("RightClick"), _T("ColClick")} enum GuiEventTypes {GUI_EVENT_NONE // NONE must be zero for any uses of ZeroMemory(), synonymous with false, etc. , GUI_EVENT_NORMAL, GUI_EVENT_DBLCLK // Try to avoid changing this and the other common ones in case anyone automates a script via SendMessage (though that does seem very unlikely). , GUI_EVENT_RCLK, GUI_EVENT_COLCLK , GUI_EVENT_FIRST_UNNAMED // This item must always be 1 greater than the last item that has a name in the GUI_EVENT_NAMES array below. , GUI_EVENT_DROPFILES = GUI_EVENT_FIRST_UNNAMED , GUI_EVENT_CLOSE, GUI_EVENT_ESCAPE, GUI_EVENT_RESIZE, GUI_EVENT_CONTEXTMENU , GUI_EVENT_DIGIT_0 = 48}; // Here just as a reminder that this value and higher are reserved so that a single printable character or digit (mnemonic) can be sent, and also so that ListView's "I" notification can add extra data into the high-byte (which lies just to the left of the "I" character in the bitfield). #endif typedef USHORT CoordModeType; // Bit-field offsets: #ifndef MINIDLL #define COORD_MODE_PIXEL 0 #endif #define COORD_MODE_MOUSE 2 #define COORD_MODE_TOOLTIP 4 #define COORD_MODE_CARET 6 #ifndef MINIDLL #define COORD_MODE_MENU 8 #endif #define COORD_MODE_WINDOW 0 #define COORD_MODE_CLIENT 1 #define COORD_MODE_SCREEN 2 #define COORD_MODE_MASK 3 #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; } // Same reason as above struct. It's best to keep this struct as small as possible // because it's used as a local (stack) var by at least one recursive function: // Each instance of this struct generally corresponds to a quasi-thread. The function that creates // a new thread typically saves the old thread's struct values on its stack so that they can later // be copied back into the g struct when the thread is resumed: class Func; // Forward declarations struct FuncAndToken { ExprTokenType mToken ; LPTSTR result_to_return_dll; Func * mFunc ; VARIANT variant_to_return_dll; }; class Label; // class Line; // struct RegItemStruct; // struct LoopReadFileStruct; // #ifndef MINIDLL class GuiType; // #endif struct global_struct { // 8-byte items are listed first, which might improve alignment for 64-bit processors (dubious). __int64 LinesPerCycle; // Use 64-bits for this so that user can specify really large values. __int64 mLoopIteration; // Signed, since script/ITOA64 aren't designed to handle unsigned. WIN32_FIND_DATA *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. // v1.0.44.14: The above mLoop attributes were moved into this structure from the script class // because they're more appropriate as thread-attributes rather than being global to the entire script. TitleMatchModes TitleMatchMode; int IntervalBeforeRest; int UninterruptedLineCount; // Stored as a g-struct attribute in case OnExit sub interrupts it while uninterruptible. int Priority; // This thread's priority relative to others. DWORD LastError; // The result of GetLastError() after the most recent DllCall or Run. #ifndef MINIDLL GuiEventType GuiEvent; // This thread's triggering event, e.g. DblClk vs. normal click. #endif EventInfoType EventInfo; // Not named "GuiEventInfo" because it applies to non-GUI events such as clipboard. #ifndef MINIDLL POINT GuiPoint; // The position of GuiEvent. Stored as a thread vs. window attribute so that underlying threads see their original values when resumed. GuiType *GuiWindow; // The GUI window that launched this thread. GuiType *GuiDefaultWindow; // This thread's default GUI window, used except when specified "Gui, 2:Add, ..." GuiType *GuiDefaultWindowValid(); // Updates and returns GuiDefaultWindow in case "Gui, Name: Default" wasn't used or the Gui has been destroyed; returns NULL if GuiDefaultWindow is invalid. GuiType *DialogOwner; // This thread's GUI owner, if any. GuiIndexType GuiControlIndex; // The GUI control index that launched this thread. #define THREAD_DIALOG_OWNER (GuiType::ValidGui(::g->DialogOwner) ? ::g->DialogOwner->mHwnd : NULL) #endif 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; // TCHAR FormatFloat[32]; Func *CurrentFunc; // v1.0.46.16: The function whose body is currently being processed at load-time, or being run at runtime (if any). Func *CurrentFuncGosub; // v1.0.48.02: Allows A_ThisFunc to work even when a function Gosubs an external subroutine. Label *CurrentLabel; // The label that is currently awaiting its matching "return" (if any). HWND hWndLastUsed; // In many cases, it's better to use GetValidLastUsedWindow() when referring to this. //HWND hWndToRestore; int MsgBoxResult; // Which button was pressed in the most recent MsgBox. HWND DialogHWND; // All these one-byte members are kept adjacent to make the struct smaller, which helps conserve stack space: SendModes SendMode; DWORD PeekFrequency; // DWORD vs. UCHAR might improve performance a little since it's checked so often. DWORD ThreadStartTime; int UninterruptibleDuration; // Must be int to preserve negative values found in g_script.mUninterruptibleTime. DWORD CalledByIsDialogMessageOrDispatchMsg; // Detects that fact that some messages (like WM_KEYDOWN->WM_NOTIFY for UpDown controls) are translated to different message numbers by IsDialogMessage (and maybe Dispatch too). bool CalledByIsDialogMessageOrDispatch; // Helps avoid launching a monitor function twice for the same message. This would probably be okay if it were a normal global rather than in the g-struct, but due to messaging complexity, this lends peace of mind and robustness. 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 AllowThreadToBeInterrupted; // Whether this thread can be interrupted by custom menu items, hotkeys, or timers. 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; CoordModeType CoordMode; // Bitwise collection of flags. UCHAR StringCaseSense; // On/Off/Locale bool StoreCapslockMode; bool AutoTrim; char FormatInt; SendLevelType SendLevel; bool MsgBoxTimedOut; // Doesn't require initialization. bool IsPaused; // The latter supports better toggling via "Pause" or "Pause Toggle". bool ListLinesIsEnabled; UINT Encoding; ExprTokenType* ThrownToken; Line* ExcptLine; bool InTryBlock; }; inline void global_maximize_interruptibility(global_struct &g) { g.AllowThreadToBeInterrupted = true; g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.ThreadIsCritical = false; g.AllowTimers = true; #define PRIORITY_MINIMUM INT_MIN g.Priority = PRIORITY_MINIMUM; // Ensure minimum priority so that it can always be interrupted. } inline void global_clear_state(global_struct &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 ErrorLevel shouldn't). { g.CurrentFunc = NULL; g.CurrentFuncGosub = NULL; g.CurrentLabel = NULL; g.hWndLastUsed = NULL; //g.hWndToRestore = NULL; g.MsgBoxResult = 0; g.IsPaused = false; g.UninterruptedLineCount = 0; #ifndef MINIDLL g.DialogOwner = NULL; #endif g.CalledByIsDialogMessageOrDispatch = false; // CalledByIsDialogMessageOrDispatchMsg doesn't need to be cleared because it's value is only considered relevant when CalledByIsDialogMessageOrDispatch==true. #ifndef MINIDLL g.GuiDefaultWindow = NULL; #endif // Above line is done because allowing it to be permanently changed by the auto-exec section // seems like it would cause more confusion that it's worth. A change to the global default // or even an override/always-use-this-window-number mode can be added if there is ever a // demand for it. 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.InTryBlock = false; } inline void global_init(global_struct &g) // This isn't made a real constructor to avoid the overhead, since there are times when we // want to declare a local var of type global_struct without having it initialized. { // 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: global_clear_state(g); g.SendMode = SM_EVENT; // v1.0.43: Default to SM_EVENT for backward compatibility. g.TitleMatchMode = FIND_IN_LEADING_PART; // Standard default for AutoIt2 and 3. 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. // Not sure what the optimal default is. 1 seems too low (scripts would be very slow by default): g.LinesPerCycle = -1; g.IntervalBeforeRest = 10; // sleep for 10ms every 10ms #define DEFAULT_PEEK_FREQUENCY 5 g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; // v1.0.46. See comments in ACT_CRITICAL. g.AllowThreadToBeInterrupted = true; // Separate from g_AllowInterruption so that they can have independent values. g.UninterruptibleDuration = 0; // 0 means uninterruptibility times out instantly. Some callers may want this so that this "g" can be used to launch other threads (e.g. threadless callbacks) using 0 as their default. g.AllowTimers = true; g.ThreadIsCritical = false; g.Priority = 0; g.LastError = 0; #ifndef MINIDLL g.GuiEvent = GUI_EVENT_NONE; #endif g.EventInfo = NO_EVENT_INFO; #ifndef MINIDLL g.GuiPoint.x = COORD_UNSPECIFIED; g.GuiPoint.y = COORD_UNSPECIFIED; // For these, indexes rather than pointers are stored because handles can become invalid during the // lifetime of a thread (while it's suspended, or if it destroys the control or window that created itself): g.GuiWindow = NULL; g.GuiControlIndex = NO_CONTROL_INDEX; // Default to out-of-bounds. g.GuiDefaultWindow = NULL; #endif 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.StringCaseSense = SCS_INSENSITIVE; // AutoIt2 default, and it does seem best. g.StoreCapslockMode = true; // AutoIt2 (and probably 3's) default, and it makes a lot of sense. g.AutoTrim = true; // AutoIt2's default, and overall the best default in most cases. _tcscpy(g.FormatFloat, _T("%0.6f")); g.FormatInt = 'D'; g.SendLevel = 0; - g.ListLinesIsEnabled = true; + g.ListLinesIsEnabled = false; g.Encoding = CP_ACP; // For FormatFloat: // I considered storing more than 6 digits to the right of the decimal point (which is the default // for most Unices and MSVC++ it seems). But going beyond that makes things a little weird for many // numbers, due to the inherent imprecision of floating point storage. For example, 83648.4 divided // by 2 shows up as 41824.200000 with 6 digits, but might show up 41824.19999999999700000000 with // 20 digits. The extra zeros could be chopped off the end easily enough, but even so, going beyond // 6 digits seems to do more harm than good for the avg. user, overall. A default of 6 is used here // in case other/future compilers have a different default (for backward compatibility, we want // 6 to always be in effect as the default for future releases). } #define ERRORLEVEL_SAVED_SIZE 128 // The size that can be remembered (saved & restored) if a thread is interrupted. Big in case user put something bigger than a number in g_ErrorLevel. #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) // 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
tinku99/ahkdll
57edb03c8c4dfff006bf9cbe1f9d7cc4b25a735c
Load Library functions also from Main exe resources
diff --git a/source/resources/AutoHotkey.rc b/source/resources/AutoHotkey.rc index 4c8d6bb..9e04be2 100644 --- a/source/resources/AutoHotkey.rc +++ b/source/resources/AutoHotkey.rc @@ -1,241 +1,241 @@ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // //#include "afxres.h" #include <winresrc.h> ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 ///////////////////////////////////////////////////////////////////////////// // // RT_MANIFEST // #ifdef EMBED_MANIFEST // VC++ 2005 and later don't require the next line. CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "AutoHotkey.exe.manifest" #endif // TYPELIB // ReleaseDll must be build before DebugDll to update .tlb file #ifdef _USRDLL #ifdef _WIN64 1 TYPELIB "temp\\x64\\ReleaseDll\\AutoHotkey.tlb" #else #ifdef _UNICODE 1 TYPELIB "temp\\Win32\\ReleaseDll\\AutoHotkey.tlb" #else 1 TYPELIB "temp\\Win32\\ReleaseDll(mbcs)\\AutoHotkey.tlb" #endif #endif #endif #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "//#include ""afxres.h""\r\n" "#include <winresrc.h>\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #ifndef MINIDLL ///////////////////////////////////////////////////////////////////////////// // // Menu // IDR_MENU_MAIN MENU BEGIN POPUP "&File" BEGIN MENUITEM "&Reload Script\tCtrl+R", ID_FILE_RELOADSCRIPT MENUITEM "&Edit Script\tCtrl+E", ID_FILE_EDITSCRIPT MENUITEM "&Window Spy", ID_FILE_WINDOWSPY MENUITEM SEPARATOR MENUITEM "&Pause Script\tPause", ID_FILE_PAUSE MENUITEM "&Suspend Hotkeys", ID_FILE_SUSPEND MENUITEM SEPARATOR MENUITEM "E&xit (Terminate Script)", ID_FILE_EXIT END POPUP "&View" BEGIN MENUITEM "&Lines most recently executed\tCtrl+L", ID_VIEW_LINES MENUITEM "&Variables and their contents\tCtrl+V", ID_VIEW_VARIABLES MENUITEM "&Hotkeys and their methods\tCtrl+H", ID_VIEW_HOTKEYS MENUITEM "&Key history and script info\tCtrl+K", ID_VIEW_KEYHISTORY MENUITEM SEPARATOR MENUITEM "&Refresh\tF5", ID_VIEW_REFRESH END POPUP "&Help" BEGIN MENUITEM "&User Manual\tF1", ID_HELP_USERMANUAL MENUITEM "&Web Site", ID_HELP_WEBSITE END END ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_MAIN ICON "icon_main.ico" IDI_SUSPEND ICON "icon_suspend.ico" IDI_PAUSE ICON "icon_pause.ico" IDI_PAUSE_SUSPEND ICON "icon_pause_suspend.ico" IDI_FILETYPE ICON "icon_filetype.ico" IDI_TRAY_WIN9X ICON "icon_tray_win9x.ico" IDI_TRAY_WIN9X_SUSPEND ICON "icon_tray_win9x_suspend.ico" IDI_TRAY ICON "icon_tray.ico" ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_INPUTBOX DIALOGEX 0, 0, 210, 83 STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME CAPTION "Dialog" FONT 10, "MS Shell Dlg", 400, 0, 0x0 BEGIN EDITTEXT IDC_INPUTEDIT,2,51,207,12,ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,51,67,31,12 PUSHBUTTON "Cancel",IDCANCEL,129,67,31,12 LTEXT "Prompt",IDC_INPUTPROMPT,3,2,205,48 END ///////////////////////////////////////////////////////////////////////////// // // Accelerator // IDR_ACCELERATOR1 ACCELERATORS BEGIN VK_F1, ID_HELP_USERMANUAL, VIRTKEY, NOINVERT "H", ID_VIEW_HOTKEYS, VIRTKEY, CONTROL, NOINVERT "K", ID_VIEW_KEYHISTORY, VIRTKEY, CONTROL, NOINVERT "L", ID_VIEW_LINES, VIRTKEY, CONTROL, NOINVERT VK_F5, ID_VIEW_REFRESH, VIRTKEY, NOINVERT "V", ID_VIEW_VARIABLES, VIRTKEY, CONTROL, NOINVERT VK_PAUSE, ID_FILE_PAUSE, VIRTKEY, NOINVERT "E", ID_FILE_EDITSCRIPT, VIRTKEY, CONTROL, NOINVERT "R", ID_FILE_RELOADSCRIPT, VIRTKEY, CONTROL, NOINVERT END #endif ///////////////////////////////////////////////////////////////////////////// // // Version // #include "..\ahkversion.h" VS_VERSION_INFO VERSIONINFO FILEVERSION AHK_VERSION_N PRODUCTVERSION AHK_VERSION_N FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN #ifdef AUTOHOTKEYSC - VALUE "FileDescription", "" + VALUE "FileDescription", " " VALUE "FileVersion", AHK_VERSION - VALUE "InternalName", "" + VALUE "InternalName", " " VALUE "LegalCopyright", "" - VALUE "OriginalFilename", "" - VALUE "ProductName", "" + VALUE "OriginalFilename", " " + VALUE "ProductName", " " VALUE "ProductVersion", AHK_VERSION #else VALUE "FileDescription", "AutoHotkey_H" VALUE "FileVersion", AHK_VERSION VALUE "InternalName", "AutoHotkey_H" VALUE "LegalCopyright", "Copyright (C) 2010" #ifdef USRDLL #ifdef MINIDLL VALUE "OriginalFilename", "AutoHotkeyMini.dll" #else VALUE "OriginalFilename", "AutoHotkey.dll" #endif #else VALUE "OriginalFilename", "AutoHotkey.exe" #endif VALUE "ProductName", "AutoHotkey_H" VALUE "ProductVersion", AHK_VERSION #endif END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED // AutoHotkey debugging script #ifdef _DEBUG #ifndef _USRDLL AHK RCDATA "Test\\Test.ahk" #endif #endif \ No newline at end of file diff --git a/source/script.cpp b/source/script.cpp index 15b7e61..57e0c80 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -9052,1053 +9052,1070 @@ ResultType Script::DefineFunc(LPTSTR aBuf, Var *aFuncGlobalVar[]) ResultType Script::DefineClass(LPTSTR aBuf) { if (mClassObjectCount == MAX_NESTED_CLASSES) return ScriptError(_T("This class definition is nested too deep."), aBuf); LPTSTR cp, class_name = aBuf; Object *outer_class, *base_class = NULL; Object *&class_object = mClassObject[mClassObjectCount]; // For convenience. Var *class_var; ExprTokenType token; for (cp = aBuf; *cp && !IS_SPACE_OR_TAB(*cp); ++cp); if (*cp) { *cp = '\0'; // Null-terminate here for class_name. cp = omit_leading_whitespace(cp + 1); if (_tcsnicmp(cp, _T("extends"), 7) || !IS_SPACE_OR_TAB(cp[7])) return ScriptError(_T("Syntax error in class definition."), cp); LPTSTR base_class_name = omit_leading_whitespace(cp + 8); if (!*base_class_name) return ScriptError(_T("Missing class name."), cp); if ( !(base_class = FindClass(base_class_name)) ) return ScriptError(_T("Unknown class."), base_class_name); } // Validate the name even if this is a nested definition, for consistency. if (!Var::ValidateName(class_name, DISPLAY_NO_ERROR)) return ScriptError(_T("Invalid class name."), class_name); class_object = NULL; // This initializes the entry in the mClassObject array. if (mClassObjectCount) // Nested class definition. { outer_class = mClassObject[mClassObjectCount - 1]; if (outer_class->GetItem(token, class_name)) // At this point it can only be an Object() created by a class definition. class_object = (Object *)token.object; } else // Top-level class definition. { *mClassName = '\0'; // Init. if ( !(class_var = FindOrAddVar(class_name)) ) return FAIL; if (class_var->IsObject()) // At this point it can only be an Object() created by a class definition. class_object = (Object *)class_var->Object(); else // Force the variable to be super-global rather than passing this flag to // FindOrAddVar: a prior reference to this variable may have created it as // an ordinary global. class_var->Scope() = VAR_DECLARE_SUPER_GLOBAL; } if (_tcslen(mClassName) + _tcslen(class_name) + 1 >= _countof(mClassName)) // +1 for '.' return ScriptError(_T("Full class name is too long.")); if (*mClassName) _tcscat(mClassName, _T(".")); _tcscat(mClassName, class_name); // For now, it seems more useful to detect a duplicate as an error rather than as // a continuation of the previous definition. Partial definitions might be allowed // in future, perhaps via something like "Class Foo continued". if (class_object) return ScriptError(_T("Duplicate class definition."), aBuf); token.symbol = SYM_STRING; token.marker = mClassName; if ( !(class_object = Object::Create()) || !(class_object->SetItem(_T("__Class"), token)) || !(mClassObjectCount ? outer_class->SetItem(class_name, class_object) // Assign to super_class[class_name]. : class_var->Assign(class_object)) ) // Assign to global variable named %class_name%. return ScriptError(ERR_OUTOFMEM); class_object->SetBase(base_class); // May be NULL. ++mClassObjectCount; return OK; } ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic) { Object *class_object = mClassObject[mClassObjectCount - 1]; LPTSTR item, item_end; TCHAR orig_char, buf[LINE_SIZE]; size_t buf_used = 0; ExprTokenType temp_token, empty_token, int_token; empty_token.symbol = SYM_STRING; empty_token.marker = _T(""); int_token.symbol = SYM_INTEGER; // Value used to mark instance variables. int_token.value_int64 = 1; // for (item = omit_leading_whitespace(aBuf); *item;) // FOR EACH COMMA-SEPARATED ITEM IN THE DECLARATION LIST. { for (item_end = item; cisalnum(*item_end) || *item_end == '_'; ++item_end); // Find end of identifier. if (item_end == item) return ScriptError(ERR_INVALID_CLASS_VAR, item); orig_char = *item_end; *item_end = '\0'; // Temporarily terminate. if (class_object->GetItem(temp_token, item)) return ScriptError(ERR_DUPLICATE_DECLARATION, item); // Assigning class_object[item] := "" is sufficient to mark it as a class variable: if (!class_object->SetItem(item, aStatic ? empty_token : int_token)) return ScriptError(ERR_OUTOFMEM); *item_end = orig_char; // Undo termination. size_t name_length = item_end - item; // This section is very similar to the on in ParseAndAddLine() which deals with // variable declarations, so maybe maintain them together: item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'. switch (*item_end) { case ',': // No initializer is present for this variable, so move on to the next one. item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration. continue; // No further processing needed below. case '\0': // No initializer is present for this variable, so move on to the next one. item = item_end; // Set "item" for use by the loop's condition. continue; case '=': // Supported for consistency with v1 syntax; to be removed in v2. ++item_end; // Point to the character after the "=". break; case ':': if (item_end[1] == '=') { item_end += 2; // Point to the character after the ":=". break; } // Otherwise, fall through to below: default: return ScriptError(ERR_INVALID_CLASS_VAR, item); } // Since above didn't "continue", this declared variable also has an initializer. // Append the class name, ":=" and initializer to pending_buf, to be turned into // an expression below, and executed at script start-up. item_end = omit_leading_whitespace(item_end); LPTSTR right_side_of_operator = item_end; // Save for use below. item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string). // Append "ClassNameOrThis.VarName := Initializer, " to the buffer. int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ") , aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator); if (chars_written < 0) return ScriptError(_T("Declaration too long.")); // Short message since should be rare. buf_used += chars_written; // Set "item" for use by the next iteration: item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list. ? omit_leading_whitespace(item_end + 1) : item_end; // It's the terminator, so let the loop detect that to finish. } if (buf_used) { // Above wrote at least one initializer expression into buf. buf[buf_used -= 2] = '\0'; // Remove the final ", " // The following section temporarily replaces mLastLine in order to insert script lines // either at the end of the list of static initializers (separate from the main script) // or at the end of the __Init method belonging to this class. Save the current values: Line *script_first_line = mFirstLine, *script_last_line = mLastLine; Line *block_end; Func *init_func = NULL; if (aStatic) { mLastLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } else { ExprTokenType token; if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT && (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability. { // __Init method already exists, so find the end of its body. for (block_end = init_func->mJumpToLine; block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute; block_end = block_end->mNextLine); } else { // Create an __Init method for this class. TCHAR def[] = _T("__Init()"); if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN) || (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation. return FAIL; mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out. init_func = g->CurrentFunc; init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions. if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL. return FAIL; block_end = mLastLine; block_end->mLineNumber = 0; // See above. // These must be updated as one or both have changed: script_first_line = mFirstLine; script_last_line = mLastLine; } g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this. mLastLine = block_end->mPrevLine; // i.e. insert before block_end. mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless. } if (!ParseAndAddLine(buf, ACT_EXPRESSION)) return FAIL; // Above already displayed the error. if (aStatic) { if (!mFirstStaticLine) mFirstStaticLine = mLastLine; mLastStaticLine = mLastLine; // The following is necessary if there weren't any executable lines above this static // initializer (i.e. mFirstLine was NULL and has been set to the newly created line): mFirstLine = script_first_line; } else { if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class. init_func->mJumpToLine = mLastLine; // Rejoin the function's block-end (and any lines following it) to the main script. mLastLine->mNextLine = block_end; block_end->mPrevLine = mLastLine; // mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our // __init function's block-begin, which is now the very first executable line in the script. g->CurrentFunc = NULL; } // Restore mLastLine so that any subsequent script lines are added at the correct point. mLastLine = script_last_line; } return OK; } Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength) { if (!aClassNameLength) aClassNameLength = _tcslen(aClassName); if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH) return NULL; LPTSTR cp, key; ExprTokenType token; Object *base_object = NULL; TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing. // Make temporary copy which we can modify. tmemcpy(class_name, aClassName, aClassNameLength); class_name[aClassNameLength] = '.'; // To simplify parsing. class_name[aClassNameLength + 1] = '\0'; // Get base variable; e.g. "MyClass" in "MyClass.MySubClass". cp = _tcschr(class_name + 1, '.'); Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL); if (!base_var) return NULL; // Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time: if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) ) return NULL; // Even if the loop below has no iterations, it initializes 'key' to the appropriate value: for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2. { if (cp == key) return NULL; // ScriptError(_T("Missing name."), cp); *cp = '\0'; // Terminate at the delimiting dot. if (!base_object->GetItem(token, key)) return NULL; base_object = (Object *)token.object; // See comment about Object() above. } return base_object; } #ifndef AUTOHOTKEYSC struct FuncLibrary { LPTSTR path; DWORD_PTR length; }; Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude) // Caller must ensure that aFuncName doesn't already exist as a defined function. // If aFuncNameLength is 0, the entire length of aFuncName is used. { aErrorWasShown = false; // Set default for this output parameter. aFileWasFound = false; int i; LPTSTR char_after_last_backslash, terminate_here; TCHAR buf[MAX_PATH+1]; DWORD attr; #define FUNC_LIB_EXT _T(".ahk") #define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1) #define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash. #define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1) #define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash. #define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1) #define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash. #define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1) #define FUNC_LIB_COUNT 4 static FuncLibrary sLib[FUNC_LIB_COUNT] = {0}; if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance. { for (i = 0; i < FUNC_LIB_COUNT; ++i) if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name. return NULL; // Due to rarity, simply pass the failure back to caller. FuncLibrary *this_lib; // DETERMINE PATH TO "LOCAL" LIBRARY: this_lib = sLib; // For convenience and maintainability. this_lib->length = BIV_ScriptDir(NULL, _T("")); if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH) { this_lib->length = BIV_ScriptDir(this_lib->path, _T("")); _tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB); this_lib->length += FUNC_LOCAL_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "USER" LIBRARY: this_lib++; // For convenience and maintainability. this_lib->length = BIV_MyDocuments(this_lib->path, _T("")); if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB); this_lib->length += FUNC_USER_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "STANDARD" LIBRARY: this_lib++; // For convenience and maintainability. GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe. char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked. this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash. if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB); this_lib->length += FUNC_STD_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY: this_lib++; // For convenience and maintainability. BIV_AhkPath(this_lib->path, _T("")); _tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk")); *(_tcsrchr(this_lib->path,'\\')+8) = '\0'; CoInitialize(NULL); IShellLink *psl; if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) { #ifdef UNICODE if (SUCCEEDED(ppf->Load(this_lib->path, 0))) #else WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed. ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes. if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0))) #endif { TCHAR buf[MAX_PATH+1]; psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY); _tcscpy(this_lib->path,buf); _tcscpy(this_lib->path + _tcslen(buf),_T("\\\0")); } ppf->Release(); } psl->Release(); } CoUninitialize(); if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') ) { this_lib->length = 0; *this_lib->path = '\0'; } else this_lib->length = _tcslen(this_lib->path); for (i = 0; i < FUNC_LIB_COUNT; ++i) { attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code. if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order. { *sLib[i].path = '\0'; // Mark this library as disabled. sLib[i].length = 0; // } } } // Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library"). if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1]; LPTSTR naked_filename = aFuncName; // Set up for the first iteration. size_t naked_filename_length = aFuncNameLength; // for (int second_iteration = 0; second_iteration < 2; ++second_iteration) { for (i = 0; i < FUNC_LIB_COUNT; ++i) { if (!*sLib[i].path) // Library is marked disabled, so skip it. continue; if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH) continue; // Path too long to match in this library, but try others. dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path. _tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension. attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern. if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order. continue; aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found. // Since above didn't "continue", a file exists whose name matches that of the requested function. // Before loading/including that file, set the working directory to its folder so that if it uses // #Include, it will be able to use more convenient/intuitive relative paths. This is similar to // the "#Include DirName" feature. // Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like // C: that lacks a backslash (see SetWorkingDir() for details). terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library. *terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir(). SetWorkingDir(sLib[i].path); // See similar section in the #Include directive. *terminate_here = '\\'; // Undo the termination. if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude) { // For each auto-included library-file, write out two #Include lines: // 1) Use #Include in its "change working directory" mode so that any explicit #include directives // or FileInstalls inside the library file itself will work consistently and properly. // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include // the library file itself. // We don't directly append library files onto the main script here because: // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files // might contain #Include even though it's rare). // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file // and deposited separately/synchronously into the temp-include file by some new logic at the // AutoHotkey.exe's code for the #Include directive. // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts. mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n") , sLib[i].length, sLib[i].path, sLib[i].path); // Now continue on normally so that our caller can continue looking for syntax errors. } // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } // Now that a matching filename has been found, it seems best to stop searching here even if that // file doesn't actually contain the requested function. This helps library authors catch bugs/typos. return FindFunc(aFuncName, aFuncNameLength); } // for() each library directory. // Now that the first iteration is done, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. break; // All loops are done because second iteration is the last possible attempt. naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). break; // All loops are done because second iteration is the last possible attempt. naked_filename = class_name_buf; // Point it to a buffer for use below. tmemcpy(naked_filename, aFuncName, naked_filename_length); naked_filename[naked_filename_length] = '\0'; } // 2-iteration for(). // HotKeyIt find library in Resource // Since above didn't return, no match found in any library. // Search in Resource for a library + // + // If using dll, first try find function in dll resource, then function + underscore (function_) in dll resource + // If nothing in dll resource is found, search again in main executable. tmemcpy(class_name_buf, aFuncName, aFuncNameLength); tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4); class_name_buf[aFuncNameLength + 4] = '\0'; - HRSRC lib_hResource; + HRSRC lib_hResource,lib_hResourceMain = NULL; if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) { + // Search main executable its resources for the function in advance. + lib_hResourceMain = FindResource(NULL, class_name_buf, _T("LIB")); // Now that the resource is not found, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. - if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. - return NULL; - naked_filename_length = first_underscore - aFuncName; - if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). - return NULL; - tmemcpy(class_name_buf, aFuncName, naked_filename_length); - tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4); - class_name_buf[naked_filename_length + 4] = '\0'; - if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) + if ( !(first_underscore = _tcschr(aFuncName, '_')) && !lib_hResourceMain ) // No second iteration needed. + { return NULL; + } + else if (first_underscore) + { + naked_filename_length = first_underscore - aFuncName; + if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). + return NULL; + tmemcpy(class_name_buf, aFuncName, naked_filename_length); + tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4); + class_name_buf[naked_filename_length + 4] = '\0'; + if ( !(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB"))) + && !(lib_hResource = lib_hResourceMain) + && !(lib_hResource = lib_hResourceMain = FindResource(NULL, class_name_buf, _T("LIB"))) ) + return NULL; + } + else if (lib_hResourceMain) + { + // Use main resource since a function was found there. + lib_hResource = lib_hResourceMain; + } } // Now a resouce was found and it can be loaded HGLOBAL hResData; TextMem::Buffer textbuf(NULL, 0, false); - if ( !( (textbuf.mLength = SizeofResource(g_hInstance, lib_hResource)) - && (hResData = LoadResource(g_hInstance, lib_hResource)) + if ( !( (textbuf.mLength = SizeofResource(lib_hResourceMain ? NULL : g_hInstance, lib_hResource)) + && (hResData = LoadResource(lib_hResourceMain ? NULL : g_hInstance, lib_hResource)) && (textbuf.mBuffer = LockResource(hResData)) ) ) { // aErrorWasShown = true; // Do not display errors here return NULL; } aFileWasFound = true; // NOTE: Ahk2Exe strips off the UTF-8 BOM. TextMem tmem; LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR)); tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8); tmem.Read(resource_script, textbuf.mLength); if (!LoadIncludedText(resource_script)) { aFileWasFound = false; return NULL; } else { return FindFunc(aFuncName, aFuncNameLength); } } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Static"))) // lowlevel() Naveen v9. { bif = BIF_Static; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; } else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1. // By design, scripts that use OnMessage are persistent by default. Doing this here // also allows WinMain() to later detect whether this script should become #SingleInstance. // Note: Don't directly change g_AllowOnlyOneInstance here in case the remainder of the // script-loading process comes across any explicit uses of #SingleInstance, which would // override the default set here. g_persistent = true; } #ifdef ENABLE_REGISTERCALLBACK else if (!_tcsicmp(func_name, _T("RegisterCallback"))) { bif = BIF_RegisterCallback; max_params = 4; // Leave min_params at 1. } #endif else if (!_tcsicmp(func_name, _T("IsObject"))) // L31 { bif = BIF_IsObject; max_params = 10000; // Leave min_params at 1. } else if (!_tcsnicmp(func_name, _T("Obj"), 3)) // L31: See script_object.cpp for details. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("ect"))) // i.e. "Object" { bif = BIF_ObjCreate; min_params = 0; max_params = 10000; } #define BIF_OBJ_CASE(aCaseSuffix, aMinParams, aMaxParams) \ else if (!_tcsicmp(suffix, _T(#aCaseSuffix))) \ { \ bif = BIF_Obj##aCaseSuffix; \ min_params = (1 + aMinParams); \ max_params = (1 + aMaxParams); \ } // All of these functions require the "object" parameter, // but it is excluded from the counts below for clarity: BIF_OBJ_CASE(Insert, 1, 10000) // [key,] value [, value2, ...] BIF_OBJ_CASE(Remove, 0, 2) // [min_key, max_key] BIF_OBJ_CASE(MinIndex, 0, 0) BIF_OBJ_CASE(MaxIndex, 0, 0) BIF_OBJ_CASE(HasKey, 1, 1) // key BIF_OBJ_CASE(GetCapacity, 0, 1) // [key] BIF_OBJ_CASE(SetCapacity, 1, 2) // [key,] new_capacity BIF_OBJ_CASE(GetAddress, 1, 1) // key BIF_OBJ_CASE(NewEnum, 0, 0) BIF_OBJ_CASE(Clone, 0, 0) #undef BIF_OBJ_CASE else if (!_tcsicmp(suffix, _T("AddRef")) || !_tcsicmp(suffix, _T("Release"))) bif = BIF_ObjAddRefRelease; else return NULL; } else if (!_tcsicmp(func_name, _T("Array"))) { bif = BIF_ObjArray; min_params = 0;
tinku99/ahkdll
1346bbeb6e28b709454d2d2ae0ec978f7ebd9efd
Small fix for UserLib for ahktextdll in 64 bit
diff --git a/source/script.cpp b/source/script.cpp index 68b96b4..15b7e61 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,1022 +1,996 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static ExprOpFunc g_ObjNew(BIF_ObjNew, 0); static ExprOpFunc g_ObjPreInc(BIF_ObjIncDec, SYM_PRE_INCREMENT), g_ObjPreDec(BIF_ObjIncDec, SYM_PRE_DECREMENT) , g_ObjPostInc(BIF_ObjIncDec, SYM_POST_INCREMENT), g_ObjPostDec(BIF_ObjIncDec, SYM_POST_DECREMENT); ExprOpFunc g_ObjCall(BIF_ObjInvoke, IT_CALL); // Also needed in script_expression.cpp. // See Script::CreateWindows() for details about the following: typedef BOOL (WINAPI* AddRemoveClipboardListenerType)(HWND); static AddRemoveClipboardListenerType MyRemoveClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "RemoveClipboardFormatListener"); static AddRemoveClipboardListenerType MyAddClipboardListener = (AddRemoveClipboardListenerType) GetProcAddress(GetModuleHandle(_T("user32")), "AddClipboardFormatListener"); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mIsAutoIt2(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { /* //ExprTokenType aResultToken; static ExprTokenType **aParam = (ExprTokenType **)SimpleHeap::Malloc(sizeof(__int64));; ExprTokenType aThisParam[1]; aThisParam[0].symbol = SYM_STRING; aThisParam[0].marker = _T(""); aParam[0] = aThisParam; int aParamCount = 0; BIF_DynaCall(aThisParam[0], aParam, aParamCount); */ // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible. int v, i; g_script.mIsReadyToExecute = false; for (v = 0; v < mVarCount; ++v) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; mVar[v]->ConvertToNonAliasIfNecessary(); if (mVar[v]->IsObject()) mVar[v]->ReleaseObject(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; ++v) { mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) { f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; ++v) { f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel; label != NULL;label = label->mNextLabel) { Label *nextLabel = label->mNextLabel; label->mJumpToLine = NULL; label->mName = _T(""); label->mPrevLabel = NULL; } for (Line *line = g_script.mLastLine; line;) { Line *nextLine = line->mPrevLine; delete line; line = nextLine; } mFuncCount = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; #ifndef MINIDLL mFirstMenu = NULL; #endif mFirstTimer = NULL; mIsReadyToExecute = false; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; for(i=1;Line::sSourceFileCount>i;i++) // HotKeyIt: first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } #ifndef MINIDLL AddRemoveHooks(0); Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif Script::~Script(); global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif free(g_MsgMonitor); } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { #ifdef STANDALONE BIV_AhkPath(aScriptFilename,_T("")); #else // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } #endif // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { PROCESS_BASIC_INFORMATION pbi; ULONG ReturnLength; - PVOID rtlUserProcParamsAddress; - UNICODE_STRING commandLine; WCHAR *commandLineContents; HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); PFN_NT_QUERY_INFORMATION_PROCESS pfnNtQueryInformationProcess = (PFN_NT_QUERY_INFORMATION_PROCESS) GetProcAddress ( GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess"); NTSTATUS status = pfnNtQueryInformationProcess ( hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(pbi), &ReturnLength); - - if (ReadProcessMemory(hProcess, (PCHAR)pbi.PebBaseAddress + 0x10, - &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) + USHORT CommanLineLength = pbi.PebBaseAddress->ProcessParameters->CommandLine.Length; + if (CommanLineLength && ReadProcessMemory(hProcess, &pbi.PebBaseAddress->ProcessParameters->CommandLine.Buffer, + &commandLineContents, CommanLineLength, NULL)) { - /* read the CommandLine UNICODE_STRING structure */ - if (ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40, - &commandLine, sizeof(commandLine), NULL)) + int dllargc = 0; + TCHAR *param; +#ifndef _UNICODE + LPWSTR wargv = (LPWSTR) _alloca(CommanLineLength); +#endif + LPWSTR *dllargv = CommandLineToArgvW(commandLineContents,&dllargc); + if (dllargc > 1 && CommanLineLength) // Only process if parameters were given { - /* allocate memory to hold the command line */ - commandLineContents = (WCHAR *)_alloca(commandLine.Length); - /* read the command line */ - if (ReadProcessMemory(hProcess, commandLine.Buffer, - commandLineContents, commandLine.Length, NULL)) + for (int i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { - int dllargc = 0; - *(commandLineContents + commandLine.Length / 2)='\0'; #ifndef _UNICODE - LPWSTR wargv = (LPWSTR) _alloca(commandLine.Length); + param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); + WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); +#else + param = dllargv[i]; // For performance and convenience. #endif - LPWSTR *dllargv = CommandLineToArgvW(commandLineContents,&dllargc); - int i; - TCHAR *param; - if (dllargc > 1 && commandLine.Length) // Only process if parameters were given + if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) + continue; + else // since this is not a switch, the end of the [Switches] section has been reached (by design). { - for (i = 1; i < dllargc; ++i) // Start at 1 because 0 contains the program name. + if (GetFileAttributes(param) == 0xFFFFFFFF) { -#ifndef _UNICODE - param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); - WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); -#else - param = dllargv[i]; // For performance and convenience. -#endif - if (!_tcsncmp(param, _T("/"),1) || !_tcsncmp(param, _T("-"),1)) - continue; - else // since this is not a switch, the end of the [Switches] section has been reached (by design). - { - if (GetFileAttributes(param) == 0xFFFFFFFF) - { - if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path - GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty - } - else - { - _tcscpy(buf,param); - } - break; // No more switches allowed after this point. - } + if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path + GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } + else + { + _tcscpy(buf,param); + } + break; // No more switches allowed after this point. } - else - { - if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path - GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty - } - } - else - { - if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path - GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } } else { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } } else { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } CloseHandle(hProcess); } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. size_t filename_length = _tcslen(filename_marker); #ifndef _USRDLL if ( mIsAutoIt2 = (filename_length >= 4 && !_tcsicmp(filename_marker + filename_length - 4, EXT_AUTOIT2)) ) { // Set the old/AutoIt2 defaults for maximum safety and compatibility. // Standalone EXEs (compiled scripts) are always considered to be non-AutoIt2 (otherwise, // the user should probably be using the AutoIt2 compiler). g_AllowSameLineComments = false; g_EscapeChar = '\\'; g.TitleFindFast = true; // In case the normal default is false. g.DetectHiddenText = false; // Make the mouse fast like AutoIt2, but not quite insta-move. 2 is expected to be more // reliable than 1 since the AutoIt author said that values less than 2 might cause the // drag to fail (perhaps just for specific apps, such as games): g.DefaultMouseSpeed = 2; g.KeyDelay = 20; g.WinDelay = 500; g.LinesPerCycle = 1; g.IntervalBeforeRest = -1; // i.e. this method is disabled by default for AutoIt2 scripts. // Reduce max params so that any non escaped delimiters the user may be using literally // in "window text" will still be considered literal, rather than as delimiters for // args that are not supported by AutoIt2, such as exclude-title, exclude-text, MsgBox // timeout, etc. Note: Don't need to change IfWinExist and such because those already // have special handling to recognize whether exclude-title is really a valid command // instead (e.g. IfWinExist, title, text, Gosub, something). // NOTE: DO NOT ADD the IfWin command series to this section, since there is special handling // for parsing those commands to figure out whether they're being used in the old AutoIt2 // style or the new Exclude Title/Text mode. // v1.0.40.02: The following is no longer done because a different mechanism is required now // that the ARGn macros do not check whether mArgc is too small and substitute an empty string // (instead, there is a loop in ExpandArgs that puts an empty string in each sArgDeref entry // for which the script omitted a parameter [and that loop relies on MaxParams being absolutely // accurate rather than conditional upon whether the script is of type ".aut"]). //g_act[ACT_FILESELECTFILE].MaxParams -= 2; //g_act[ACT_FILEREMOVEDIR].MaxParams -= 1; //g_act[ACT_MSGBOX].MaxParams -= 1; //g_act[ACT_INIREAD].MaxParams -= 1; //g_act[ACT_STRINGREPLACE].MaxParams -= 1; //g_act[ACT_STRINGGETPOS].MaxParams -= 2; //g_act[ACT_WINCLOSE].MaxParams -= 3; // -3 for these two, -2 for the others. //g_act[ACT_WINKILL].MaxParams -= 3; //g_act[ACT_WINACTIVATE].MaxParams -= 2; //g_act[ACT_WINMINIMIZE].MaxParams -= 2; //g_act[ACT_WINMAXIMIZE].MaxParams -= 2; //g_act[ACT_WINRESTORE].MaxParams -= 2; //g_act[ACT_WINHIDE].MaxParams -= 2; //g_act[ACT_WINSHOW].MaxParams -= 2; //g_act[ACT_WINSETTITLE].MaxParams -= 2; //g_act[ACT_WINGETTITLE].MaxParams -= 2; } #endif if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if ( !(g_array = (global_struct *)malloc((g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "background thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT);
tinku99/ahkdll
cb60f1ab11f827f7f27f889fb0e4e7c9014cabfb
gitignore dll
diff --git a/.gitignore b/.gitignore index 3a8bb4d..428498a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,11 @@ AutoHotkey.sdf *.opensdf +*.dll AutoHotkey.suo AutoHotkey.vcxproj.user ComServer_h.h ComServer_i.c Test bin ipch temp
tinku99/ahkdll
3afee9ed8cffe0118b24a2ac39b42ad5e8aa448e
readded comobjarray
diff --git a/source/script.cpp b/source/script.cpp index cbfade8..1266bb1 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -9553,1079 +9553,1083 @@ Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool & else { return FindFunc(aFuncName, aFuncNameLength); } } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL /* if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } */ if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } /* else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Static"))) // lowlevel() Naveen v9. { bif = BIF_Static; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } */ else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } /* else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; } */ else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; /* else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; */ else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; /* #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } */ else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; /* else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1. // By design, scripts that use OnMessage are persistent by default. Doing this here // also allows WinMain() to later detect whether this script should become #SingleInstance. // Note: Don't directly change g_AllowOnlyOneInstance here in case the remainder of the // script-loading process comes across any explicit uses of #SingleInstance, which would // override the default set here. g_persistent = true; } #ifdef ENABLE_REGISTERCALLBACK else if (!_tcsicmp(func_name, _T("RegisterCallback"))) { bif = BIF_RegisterCallback; max_params = 4; // Leave min_params at 1. } #endif */ else if (!_tcsicmp(func_name, _T("IsObject"))) // L31 { bif = BIF_IsObject; max_params = 10000; // Leave min_params at 1. } else if (!_tcsnicmp(func_name, _T("Obj"), 3)) // L31: See script_object.cpp for details. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("ect"))) // i.e. "Object" { bif = BIF_ObjCreate; min_params = 0; max_params = 10000; } #define BIF_OBJ_CASE(aCaseSuffix, aMinParams, aMaxParams) \ else if (!_tcsicmp(suffix, _T(#aCaseSuffix))) \ { \ bif = BIF_Obj##aCaseSuffix; \ min_params = (1 + aMinParams); \ max_params = (1 + aMaxParams); \ } // All of these functions require the "object" parameter, // but it is excluded from the counts below for clarity: BIF_OBJ_CASE(Insert, 1, 10000) // [key,] value [, value2, ...] BIF_OBJ_CASE(Remove, 0, 2) // [min_key, max_key] BIF_OBJ_CASE(MinIndex, 0, 0) BIF_OBJ_CASE(MaxIndex, 0, 0) BIF_OBJ_CASE(HasKey, 1, 1) // key BIF_OBJ_CASE(GetCapacity, 0, 1) // [key] BIF_OBJ_CASE(SetCapacity, 1, 2) // [key,] new_capacity BIF_OBJ_CASE(GetAddress, 1, 1) // key BIF_OBJ_CASE(NewEnum, 0, 0) BIF_OBJ_CASE(Clone, 0, 0) #undef BIF_OBJ_CASE else if (!_tcsicmp(suffix, _T("AddRef")) || !_tcsicmp(suffix, _T("Release"))) bif = BIF_ObjAddRefRelease; else return NULL; } else if (!_tcsicmp(func_name, _T("Array"))) { bif = BIF_ObjArray; min_params = 0; max_params = 10000; } /* else if (!_tcsicmp(func_name, _T("FileOpen"))) { bif = BIF_FileOpen; min_params = 2; max_params = 3; } - + */ else if (!_tcsnicmp(func_name, _T("ComObj"), 6)) { suffix = func_name + 6; + /* if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_ComObjCreate; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get"))) bif = BIF_ComObjGet; else if (!_tcsicmp(suffix, _T("Connect"))) { bif = BIF_ComObjConnect; max_params = 2; } else if (!_tcsicmp(suffix, _T("Error"))) { bif = BIF_ComObjError; min_params = 0; } else if (!_tcsicmp(suffix, _T("Type"))) { bif = BIF_ComObjTypeOrValue; max_params = 2; } else if (!_tcsicmp(suffix, _T("Value"))) { bif = BIF_ComObjTypeOrValue; } else if (!_tcsicmp(suffix, _T("Flags"))) { bif = BIF_ComObjFlags; max_params = 3; } - else if (!_tcsicmp(suffix, _T("Array"))) + */ + if (!_tcsicmp(suffix, _T("Array"))) { bif = BIF_ComObjArray; min_params = 2; max_params = 9; // up to 8 dimensions } + /* else if (!_tcsicmp(suffix, _T("Query"))) { bif = BIF_ComObjQuery; min_params = 2; max_params = 3; } else { bif = BIF_ComObjActive; min_params = 0; max_params = 3; } - } */ + } + else if (!_tcsicmp(func_name, _T("Exception"))) { bif = BIF_Exception; max_params = 3; } else return NULL; // Maint: There may be other lines above that also return NULL. // Since above didn't return, this is a built-in function that hasn't yet been added to the list. // Add it now: if ( !(pfunc = AddFunc(func_name, aFuncNameLength, true, left)) ) // L27: left contains the position within mFunc to insert the function. Cannot use *apInsertPos as caller may have omitted it or passed NULL. return NULL; pfunc->mBIF = bif; pfunc->mMinParams = min_params; pfunc->mParamCount = max_params; return pfunc; } Func *Script::AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject) // This function should probably not be called by anyone except FindOrAddFunc, which has already done // the dupe-checking. // Returns the address of the new function or NULL on failure. // The caller must already have verified that this isn't a duplicate function. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (aFuncNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Function name too long."), aFuncName); return NULL; } // Make a temporary copy that includes only the first aFuncNameLength characters from aFuncName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // See explanation above. +1 to convert length to size. // In the future, it might be best to add another check here to disallow function names that consist // entirely of numbers. However, this hasn't been done yet because: // 1) Not sure if there will ever be a good enough reason. // 2) Even if it's done in the far future, it won't break many scripts (pure-numeric functions should be very rare). // 3) Those scripts that are broken are not broken in a bad way because the pre-parser will generate a // load-time error, which is easy to fix (unlike runtime errors, which require that part of the script // to actually execute). if (!aClassObject && !Var::ValidateName(func_name, DISPLAY_FUNC_ERROR)) // Variable and function names are both validated the same way. // Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit). return NULL; // Allocate some dynamic memory to pass to the constructor: LPTSTR new_name = SimpleHeap::Malloc(func_name, aFuncNameLength); if (!new_name) // It already displayed the error for us. return NULL; Func *the_new_func = new Func(new_name, aIsBuiltIn); if (!the_new_func) { ScriptError(ERR_OUTOFMEM); return NULL; } if (aClassObject) { LPTSTR key = _tcsrchr(new_name, '.'); if (!key) { ScriptError(_T("Invalid method name."), new_name); // Shouldn't ever happen. return NULL; } if (!aClassObject->SetItem(key + 1, the_new_func)) { ScriptError(ERR_OUTOFMEM); return NULL; } // Also add it to the script's list of functions, to support #Warn LocalSameAsGlobal // and automatic cleanup of objects in static vars on program exit. } if (mFuncCount == mFuncCountMax) { // Allocate or expand function list. int alloc_count = mFuncCountMax ? mFuncCountMax * 2 : 100; Func **temp = (Func **)realloc(mFunc, alloc_count * sizeof(Func *)); // If passed NULL, realloc() will do a malloc(). if (!temp) { ScriptError(ERR_OUTOFMEM); return NULL; } mFunc = temp; mFuncCountMax = alloc_count; } if (aInsertPos != mFuncCount) // Need to make room at the indicated position for this variable. memmove(mFunc + aInsertPos + 1, mFunc + aInsertPos, (mFuncCount - aInsertPos) * sizeof(Func *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. mFunc[aInsertPos] = the_new_func; ++mFuncCount; return the_new_func; } size_t Line::ArgIndexLength(int aArgIndex) // This function is similar to ArgToInt(), so maintain them together. // "ArgLength" is the arg's fully resolved, dereferenced length during runtime. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. // ArgLength() was added in v1.0.44.14 to help its callers improve performance by avoiding // costly calls to _tcslen() (which is especially beneficial for huge strings). { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // Arg doesn't exist, so don't try accessing sArgVar (unlike sArgDeref, it wouldn't be valid to do so). return 0; // i.e. treat it as the empty string. // The length is not known and must be calculated in the following situations: // - The arg consists of more than just a single isolated variable name (not possible if the arg is // ARG_TYPE_INPUT_VAR). // - The arg is a built-in variable, in which case the length isn't known, so it must be derived from // the string copied into sArgDeref[] by an earlier stage. // - The arg is a normal variable but it's VAR_ATTRIB_BINARY_CLIP. In such cases, our callers do not // recognize/support binary-clipboard as binary and want the apparent length of the string returned // (i.e. _tcslen(), which takes into account the position of the first binary zero wherever it may be). if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; // For performance and convenience. if ( var.Type() == VAR_NORMAL // This and below ordered for short-circuit performance based on types of input expected from caller. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) // Although the ones that have the highbit set are hereby omitted from the fast method, the nature of almost all of the highbit commands is such that their performance won't be measurably affected. See ArgMustBeDereferenced() for more info. && (g_NoEnv || var.HasContents()) // v1.0.46.02: Recognize environment variables (when g_NoEnv==FALSE) by falling through to _tcslen() for them. && &var != g_ErrorLevel ) // Mostly for maintainability because the following situation is very rare: If it's g_ErrorLevel, use the deref version instead because if g_ErrorLevel is an input variable in the caller's command, and the caller changes ErrorLevel (such as to set a default) prior to calling this function, the changed/new ErrorLevel will be used rather than its original value (which is usually undesirable). //&& !var.IsBinaryClip()) // This check isn't necessary because the line below handles it. return var.LengthIgnoreBinaryClip(); // Do it the fast way (unless it's binary clipboard, in which case this call will internally call _tcslen()). } // Otherwise, length isn't known due to no variable, a built-in variable, or an environment variable. // So do it the slow way. return _tcslen(sArgDeref[aArgIndex]); } __int64 Line::ArgIndexToInt64(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0; // i.e. treat it as ATOI64(""). // SEE THIS POSITION IN ArgIndexLength() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToInt64(FALSE); } // Otherwise: return ATOI64(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } double Line::ArgIndexToDouble(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0.0; // i.e. treat it as ATOF(""). // SEE THIS POSITION IN ARGLENGTH() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToDouble(FALSE); } // Otherwise: return ATOF(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } Var *Line::ResolveVarOfArg(int aArgIndex, bool aCreateIfNecessary) // Returns NULL on failure. Caller has ensured that none of this arg's derefs are function-calls. // Args that are input or output variables are normally resolved at load-time, so that // they contain a pointer to their Var object. This is done for performance. However, // in order to support dynamically resolved variables names like AutoIt2 (e.g. arrays), // we have to do some extra work here at runtime. // Callers specify false for aCreateIfNecessary whenever the contents of the variable // they're trying to find is unimportant. For example, dynamically built input variables, // such as "StringLen, length, array%i%", do not need to be created if they weren't // previously assigned to (i.e. they weren't previously used as an output variable). // In the above example, the array element would never be created here. But if the output // variable were dynamic, our call would have told us to create it. { // The requested ARG isn't even present, so it can't have a variable. Currently, this should // never happen because the loading procedure ensures that input/output args are not marked // as variables if they are blank (and our caller should check for this and not call in that case): if (aArgIndex >= mArgc) return NULL; ArgStruct &this_arg = mArg[aArgIndex]; // For performance and convenience. // Since this function isn't inline (since it's called so frequently), there isn't that much more // overhead to doing this check, even though it shouldn't be needed since it's the caller's // responsibility: if (this_arg.type == ARG_TYPE_NORMAL) // Arg isn't an input or output variable. return NULL; if (!*this_arg.text) // The arg's variable is not one that needs to be dynamically resolved. return VAR(this_arg); // Return the var's address that was already determined at load-time. // The above might return NULL in the case where the arg is optional (i.e. the command allows // the var name to be omitted). But in that case, the caller should either never have called this // function or should check for NULL upon return. UPDATE: This actually never happens, see // comment above the "if (aArgIndex >= mArgc)" line. // Static to correspond to the static empty_var further below. It needs the memory area // to support resolving dynamic environment variables. In the following example, // the result will be blank unless the first line is present (without this fix here): //null = %SystemRoot% ; bogus line as a required workaround in versions prior to v1.0.16 //thing = SystemRoot //StringTrimLeft, output, %thing%, 0 //msgbox %output% static TCHAR sVarName[MAX_VAR_NAME_LENGTH + 1]; // Will hold the dynamically built name. // At this point, we know the requested arg is a variable that must be dynamically resolved. // This section is similar to that in ExpandArg(), so they should be maintained together: LPTSTR pText = this_arg.text; // Start at the beginning of this arg's text. size_t var_name_length = 0; if (this_arg.deref) // There's at least one deref. { // Caller has ensured that none of these derefs are function calls (i.e. deref->is_function is alway false). for (DerefType *deref = this_arg.deref // Start off by looking for the first deref. ; deref->marker; ++deref) // A deref with a NULL marker terminates the list. { // FOR EACH DEREF IN AN ARG (if we're here, there's at least one): // Copy the chars that occur prior to deref->marker into the buffer: for (; pText < deref->marker && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && pText < deref->marker) // The variable name would be too long! { // This type of error is just a warning because this function isn't set up to cause a true // failure. This is because the use of dynamically named variables is rare, and only for // people who should know what they're doing. In any case, when the caller of this // function called it to resolve an output variable, it will see the the result is // NULL and terminate the current subroutine. #define DYNAMIC_TOO_LONG _T("This dynamically built variable name is too long.") \ _T(" If this variable was not intended to be dynamic, remove the % symbols from it.") LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } // Now copy the contents of the dereferenced var. For all cases, aBuf has already // been verified to be large enough, assuming the value hasn't changed between the // time we were called and the time the caller calculated the space needed. if (deref->var->Get() > (VarSizeType)(MAX_VAR_NAME_LENGTH - var_name_length)) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } var_name_length += deref->var->Get(sVarName + var_name_length); // Finally, jump over the dereference text. Note that in the case of an expression, there might not // be any percent signs within the text of the dereference, e.g. x + y, not %x% + %y%. pText += deref->length; } } // Copy any chars that occur after the final deref into the buffer: for (; *pText && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && *pText) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } if (!var_name_length) { LineError(_T("This dynamic variable is blank. If this variable was not intended to be dynamic,") _T(" remove the % symbols from it."), FAIL, this_arg.text); return NULL; } // Terminate the buffer, even if nothing was written into it: sVarName[var_name_length] = '\0'; static Var empty_var(sVarName, (void *)VAR_NORMAL, false); // Must use sVarName here. See comment above for why. Var *found_var; if (!aCreateIfNecessary) { // Now we've dynamically build the variable name. It's possible that the name is illegal, // so check that (the name is automatically checked by FindOrAddVar(), so we only need to // check it if we're not calling that): if (!Var::ValidateName(sVarName)) return NULL; // Above already displayed error for us. if (found_var = g_script.FindVar(sVarName, var_name_length)) // Assign. return found_var; // At this point, this is either a non-existent variable or a reserved/built-in variable // that was never statically referenced in the script (only dynamically), e.g. A_IPAddress%A_Index% if (Script::GetVarType(sVarName) == (void *)VAR_NORMAL) // If not found: for performance reasons, don't create it because caller just wants an empty variable. return &empty_var; //else it's the clipboard or some other built-in variable, so continue onward so that the // variable gets created in the variable list, which is necessary to allow it to be properly // dereferenced, e.g. in a script consisting of only the following: // Loop, 4 // StringTrimRight, IP, A_IPAddress%A_Index%, 0 } // Otherwise, aCreateIfNecessary is true or we want to create this variable unconditionally for the // reason described above. if ( !(found_var = g_script.FindOrAddVar(sVarName, var_name_length)) ) return NULL; // Above will already have displayed the error. if (this_arg.type == ARG_TYPE_OUTPUT_VAR && VAR_IS_READONLY(*found_var)) { LineError(ERR_VAR_IS_READONLY, FAIL, sVarName); return NULL; // Don't return the var, preventing the caller from assigning to it. } else return found_var; } Var *Script::FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength, int aScope) // Caller has ensured that aVarName isn't NULL. // Returns the Var whose name matches aVarName. If it doesn't exist, it is created. { if (!*aVarName) return NULL; int insert_pos; bool is_local; // Used to detect which type of var should be added in case the result of the below is NULL. Var *var; if (var = FindVar(aVarName, aVarNameLength, &insert_pos, aScope, &is_local)) return var; // Otherwise, no match found, so create a new var. This will return NULL if there was a problem, // in which case AddVar() will already have displayed the error: return AddVar(aVarName, aVarNameLength, insert_pos , (aScope & ~(VAR_LOCAL | VAR_GLOBAL)) | (is_local ? VAR_LOCAL : VAR_GLOBAL)); // When aScope == FINDVAR_DEFAULT, it contains both the "local" and "global" bits. This ensures only the appropriate bit is set. } Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, int aScope , bool *apIsLocal) // Caller has ensured that aVarName isn't NULL. It must also ignore the contents of apInsertPos when // a match (non-NULL value) is returned. // Returns the Var whose name matches aVarName. If it doesn't exist, NULL is returned. // If caller provided a non-NULL apInsertPos, it will be given a the array index that a newly // inserted item should have to keep the list in sorted order (which also allows the ListVars command // to display the variables in alphabetical order). { if (!*aVarName) return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. When the caller later // tries to add the variable, it will get an error then: if (aVarNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the various searches below to use _tcsicmp() instead of // strlicmp(), which close to doubles their performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR var_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(var_name, aVarName, aVarNameLength + 1); // +1 to convert length to size. global_struct &g = *::g; // Reduces code size and may improve performance. bool search_local = (aScope & VAR_LOCAL) && g.CurrentFunc; // Above has ensured that g.CurrentFunc!=NULL whenever search_local==true. // Init for binary search loop: int left, right, mid, result; // left/right must be ints to allow them to go negative and detect underflow. Var **var; // An array of pointers-to-var. if (search_local) { var = g.CurrentFunc->mVar; right = g.CurrentFunc->mVarCount - 1; } else { var = mVar; right = mVarCount - 1; } // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } // Since above didn't return, no match was found in the main list, so search the lazy list if there // is one. If there's no lazy list, the value of "left" established above will be used as the // insertion point further below: if (search_local) { var = g.CurrentFunc->mLazyVar; right = g.CurrentFunc->mLazyVarCount - 1; } else { var = mLazyVar; right = mLazyVarCount - 1; } if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below). { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } // Since above didn't return, no match was found and "left" always contains the position where aVarName // should be inserted to keep the list sorted. The item is always inserted into the lazy list unless // there is no lazy list. // Set the output parameter, if present: if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below. *apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order. if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match. *apIsLocal = search_local; // Since no match was found, if this is a local fall back to searching the list of globals at runtime // if the caller didn't insist on a particular type: if (search_local && aScope == FINDVAR_DEFAULT) { // In this case, callers want to fall back to globals when a local wasn't found. However, // they want the insertion (if our caller will be doing one) to insert according to the // current assume-mode. Therefore, if the mode is assume-global, pass the apIsLocal // and apInsertPos variables to FindVar() so that it will update them to be global. if (g.CurrentFunc->mDefaultVarType == VAR_DECLARE_GLOBAL) return FindVar(aVarName, aVarNameLength, apInsertPos, FINDVAR_GLOBAL, apIsLocal); // v1: Each *dynamic* variable reference may resolve to a global if one exists. if (mIsReadyToExecute) return FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL); // Otherwise, caller only wants globals which are declared in *this* function: for (int i = 0; i < g.CurrentFunc->mGlobalVarCount; ++i) if (!_tcsicmp(var_name, g.CurrentFunc->mGlobalVar[i]->mName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return g.CurrentFunc->mGlobalVar[i]; // As a last resort, check for a super-global: Var *gvar = FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL, NULL); if (gvar && gvar->IsSuperGlobal()) return gvar; } // Otherwise, since above didn't return: return NULL; // No match. } Var *Script::AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope) // Returns the address of the new variable or NULL on failure. // Caller must ensure that g->CurrentFunc!=NULL whenever aIsLocal!=0. // Caller must ensure that aVarName isn't NULL and that this isn't a duplicate variable name. // In addition, it has provided aInsertPos, which is the insertion point so that the list stays sorted. // Finally, aIsLocal has been provided to indicate which list, global or local, should receive this // new variable, as well as the type of local variable. (See the declaration of VAR_LOCAL etc.) { if (!*aVarName) // Should never happen, so just silently indicate failure. return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); if (aVarNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Variable name too long."), aVarName);
tinku99/ahkdll
2ed58839689f57977e54637e06e4492df287d64f
Fixed RegClass error
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index d1478d3..349ab6f 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,619 +1,621 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR aDefaultDllScript = _T("#Persistent\n#NoTrayIcon"); static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; // Naveen v1. hThread2 and threadCount // Todo: remove these as multithreading was implemented // with multiple loading of the dll under separate names. static int threadCount = 1 ; static HANDLE hThread2; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); // Unregister window class registered in Script::CreateWindows -#ifdef UNICODE - UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); #ifndef MINIDLL - UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); -#endif // MINIDLL +#ifdef UNICODE + if (g_ClassRegistered) + UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); + if (g_ClassSplashRegistered) + UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else - UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); -#ifndef MINIDLL - UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); -#endif // MINIDLL + if (g_ClassRegistered) + UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); + if (g_ClassSplashRegistered) + UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif +#endif // MINIDLL break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(int timeout) { int lpExitCode = 0; if (hThread == 0) return 0; if (timeout < 1) timeout = 500; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < (timeout/100); i++) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0,0,(timeout/10),0); Sleep((timeout/10)); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; diff --git a/source/globaldata.cpp b/source/globaldata.cpp index 75af017..d4fa074 100644 --- a/source/globaldata.cpp +++ b/source/globaldata.cpp @@ -1,546 +1,548 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 // These includes should probably a superset of those in 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" // Since at least some of some of these (e.g. g_modifiersLR_logical) should not // be kept in the struct since it's not correct to save and restore their // state, don't keep anything in the global_struct except those things // which are necessary to save and restore (even though it would clean // up the code and might make maintaining it easier): HRSRC g_hResource = NULL; // Set by WinMain() HINSTANCE g_hInstance = NULL; // Set by WinMain(). DWORD g_MainThreadID = GetCurrentThreadId(); DWORD g_HookThreadID; // Not initialized by design because 0 itself might be a valid thread ID. +ATOM g_ClassRegistered = 0; +ATOM g_ClassSplashRegistered = 0; CRITICAL_SECTION g_CriticalRegExCache; UINT g_DefaultScriptCodepage = UorA(CP_UTF8, CP_ACP); bool g_DestroyWindowCalled = false; HWND g_hWnd = NULL; HWND g_hWndEdit = NULL; HFONT g_hFontEdit = NULL; #ifndef MINIDLL HWND g_hWndSplash = NULL; HFONT g_hFontSplash = NULL; // So that font can be deleted on program close. #endif HACCEL g_hAccelTable = NULL; typedef int (WINAPI *StrCmpLogicalW_type)(LPCWSTR, LPCWSTR); StrCmpLogicalW_type g_StrCmpLogicalW = NULL; WNDPROC g_TabClassProc = NULL; modLR_type g_modifiersLR_logical = 0; modLR_type g_modifiersLR_logical_non_ignored = 0; modLR_type g_modifiersLR_physical = 0; #ifdef FUTURE_USE_MOUSE_BUTTONS_LOGICAL WORD g_mouse_buttons_logical = 0; #endif // Used by the hook to track physical state of all virtual keys, since GetAsyncKeyState() does // not retrieve the physical state of a key. Note that this array is sometimes used in a way that // requires its format to be the same as that returned from GetKeyboardState(): BYTE g_PhysicalKeyState[VK_ARRAY_COUNT] = {0}; bool g_BlockWinKeys = false; DWORD g_HookReceiptOfLControlMeansAltGr = 0; // In these cases, zero is used as a false value, any others are true. DWORD g_IgnoreNextLControlDown = 0; // DWORD g_IgnoreNextLControlUp = 0; // BYTE g_MenuMaskKey = VK_CONTROL; // L38: See #MenuMaskKey. int g_HotkeyModifierTimeout = 50; // Reduced from 100, which was a little too large for fast typists. int g_ClipboardTimeout = 1000; // v1.0.31 HHOOK g_KeybdHook = NULL; HHOOK g_MouseHook = NULL; HHOOK g_PlaybackHook = NULL; bool g_ForceLaunch = false; bool g_WinActivateForce = false; WarnMode g_Warn_UseUnsetLocal = WARNMODE_OFF; // Used by #Warn directive. WarnMode g_Warn_UseUnsetGlobal = WARNMODE_OFF; // WarnMode g_Warn_UseEnv = WARNMODE_OFF; // WarnMode g_Warn_LocalSameAsGlobal = WARNMODE_OFF; // #ifndef MINIDLL SingleInstanceType g_AllowOnlyOneInstance = ALLOW_MULTI_INSTANCE; #endif bool g_persistent = false; // Whether the script should stay running even after the auto-exec section finishes. #ifndef MINIDLL bool g_NoTrayIcon = false; #endif #ifdef AUTOHOTKEYSC bool g_AllowMainWindow = false; #endif bool g_AllowSameLineComments = true; bool g_MainTimerExists = false; bool g_AutoExecTimerExists = false; #ifndef MINIDLL bool g_InputTimerExists = false; #endif bool g_DerefTimerExists = false; bool g_SoundWasPlayed = false; #ifndef MINIDLL bool g_IsSuspended = false; // Make this separate from g_AllowInterruption since that is frequently turned off & on. #endif bool g_DeferMessagesForUnderlyingPump = false; BOOL g_WriteCacheDisabledInt64 = FALSE; // BOOL vs. bool might improve performance a little for BOOL g_WriteCacheDisabledDouble = FALSE; // frequently-accessed variables (it has helped performance in BOOL g_NoEnv = TRUE; // HotKeyIt H5 new default BOOL g_AllowInterruption = TRUE; // int g_nLayersNeedingTimer = 0; int g_nThreads = 0; int g_nPausedThreads = 0; #ifndef MINIDLL int g_MaxHistoryKeys = 40; #endif // g_MaxVarCapacity is used to prevent a buggy script from consuming all available system RAM. It is defined // as the maximum memory size of a variable, including the string's zero terminator. // The chosen default seems big enough to be flexible, yet small enough to not be a problem on 99% of systems: VarSizeType g_MaxVarCapacity = 64 * 1024 * 1024; UCHAR g_MaxThreadsPerHotkey = 1; int g_MaxThreadsTotal = MAX_THREADS_DEFAULT; // On my system, the repeat-rate (which is probably set to XP's default) is such that between 20 // and 25 keys are generated per second. Therefore, 50 in 2000ms seems like it should allow the // key auto-repeat feature to work on most systems without triggering the warning dialog. // In any case, using auto-repeat with a hotkey is pretty rare for most people, so it's best // to keep these values conservative: #ifndef MINIDLL int g_MaxHotkeysPerInterval = 70; // Increased to 70 because 60 was still causing the warning dialog for repeating keys sometimes. Increased from 50 to 60 for v1.0.31.02 since 50 would be triggered by keyboard auto-repeat when it is set to its fastest. int g_HotkeyThrottleInterval = 2000; // Milliseconds. #endif bool g_MaxThreadsBuffer = false; // This feature usually does more harm than good, so it defaults to OFF. SendLevelType g_InputLevel = 0; #ifndef MINIDLL HotCriterionType g_HotCriterion = HOT_NO_CRITERION; LPTSTR g_HotWinTitle = _T(""); // In spite of the above being the primary indicator, LPTSTR g_HotWinText = _T(""); // these are initialized for maintainability. HotkeyCriterion *g_FirstHotCriterion = NULL, *g_LastHotCriterion = NULL; // Global variables for #if (expression). int g_HotExprIndex = -1; // The index of the Line containing the expression defined by the most recent #if (expression) directive. Line **g_HotExprLines = NULL; // Array of pointers to expression lines, allocated when needed. int g_HotExprLineCount = 0; // Number of expression lines currently present. int g_HotExprLineCountMax = 0; // Current capacity of g_HotExprLines. UINT g_HotExprTimeout = 1000; // Timeout for #if (expression) evaluation, in milliseconds. HWND g_HotExprLFW = NULL; // Last Found Window of last #if expression. MenuTypeType g_MenuIsVisible = MENU_TYPE_NONE; #endif int g_nMessageBoxes = 0; #ifndef MINIDLL int g_nInputBoxes = 0; int g_nFileDialogs = 0; int g_nFolderDialogs = 0; InputBoxType g_InputBox[MAX_INPUTBOXES]; SplashType g_Progress[MAX_PROGRESS_WINDOWS] = {{0}}; SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS] = {{0}}; GuiType **g_gui = NULL; int g_guiCount = 0, g_guiCountMax = 0; #endif HWND g_hWndToolTip[MAX_TOOLTIPS] = {NULL}; MsgMonitorStruct *g_MsgMonitor = NULL; // An array to be allocated upon first use (if any). int g_MsgMonitorCount = 0; // Init not needed for these: UCHAR g_SortCaseSensitive; bool g_SortNumeric; bool g_SortReverse; int g_SortColumnOffset; Func *g_SortFunc; TCHAR g_delimiter = ','; TCHAR g_DerefChar = '%'; TCHAR g_EscapeChar = '`'; #ifndef MINIDLL // Hot-string vars (initialized when ResetHook() is first called): TCHAR g_HSBuf[HS_BUF_SIZE]; int g_HSBufLength; HWND g_HShwnd; // Hot-string global settings: int g_HSPriority = 0; // default priority is always 0 int g_HSKeyDelay = 0; // Fast sends are much nicer for auto-replace and auto-backspace. SendModes g_HSSendMode = SM_INPUT; // v1.0.43: New default for more reliable hotstrings. bool g_HSCaseSensitive = false; bool g_HSConformToCase = true; bool g_HSDoBackspace = true; bool g_HSOmitEndChar = false; bool g_HSSendRaw = false; bool g_HSEndCharRequired = true; bool g_HSDetectWhenInsideWord = false; bool g_HSDoReset = false; bool g_HSResetUponMouseClick = true; TCHAR g_EndChars[HS_MAX_END_CHARS + 1] = _T("-()[]{}:;'\"/\\,.?!\n \t"); // Hotstring default end chars, including a space. // The following were considered but seemed too rare and/or too likely to result in undesirable replacements // (such as while programming or scripting, or in usernames or passwords): <>*+=_%^&|@#$| // Although dash/hyphen is used for multiple purposes, it seems to me that it is best (on average) to include it. // Jay D. Novak suggested ([{/ for things such as fl/nj or fl(nj) which might resolve to USA state names. // i.e. word(synonym) and/or word/synonym #endif // Global objects: Var *g_ErrorLevel = NULL; // Allows us (in addition to the user) to set this var to indicate success/failure. #ifndef MINIDLL input_type g_input; #endif Script g_script; // This made global for performance reasons (determining size of clipboard data then // copying contents in or out without having to close & reopen the clipboard in between): Clipboard g_clip; OS_Version g_os; // OS version object, courtesy of AutoIt3. // THIS MUST BE DONE AFTER the g_os object is initialized above: // These are conditional because on these OSes, only standard-palette 16-color icons are supported, // which would cause the normal icons to look mostly gray when used with in the tray. So we use // special 16x16x16 icons, but only for the tray because these OSes display the nicer icons okay // in places other than the tray. Also note that the red icons look okay, at least on Win98, // because they are "red enough" not to suffer the graying effect from the palette shifting done // by the OS: #ifndef MINIDLL int g_IconTray = (g_os.IsWinXPorLater() || g_os.IsWinMeorLater()) ? IDI_TRAY : IDI_TRAY_WIN9X; int g_IconTraySuspend = (g_IconTray == IDI_TRAY) ? IDI_SUSPEND : IDI_TRAY_WIN9X_SUSPEND; #endif DWORD g_OriginalTimeout; global_struct g_default, g_startup, *g_array; global_struct *g = &g_startup; // g_startup provides a non-NULL placeholder during script loading. Afterward it's replaced with an array. // I considered maintaining this on a per-quasi-thread basis (i.e. in global_struct), but the overhead // of having to check and restore the working directory when a suspended thread is resumed (especially // when the script has many high-frequency timers), and possibly changing the working directory // whenever a new thread is launched, doesn't seem worth it. This is because the need to change // the working directory is comparatively rare: TCHAR g_WorkingDir[MAX_PATH] = _T(""); TCHAR *g_WorkingDirOrig = NULL; // Assigned a value in WinMain(). bool g_ContinuationLTrim = false; #ifndef MINIDLL bool g_ForceKeybdHook = false; #endif ToggleValueType g_ForceNumLock = NEUTRAL; ToggleValueType g_ForceCapsLock = NEUTRAL; ToggleValueType g_ForceScrollLock = NEUTRAL; ToggleValueType g_BlockInputMode = TOGGLE_DEFAULT; bool g_BlockInput = false; bool g_BlockMouseMove = false; // The order of initialization here must match the order in the enum contained in script.h // It's in there rather than in globaldata.h so that the action-type constants can be referred // to without having access to the global array itself (i.e. it avoids having to include // globaldata.h in modules that only need access to the enum's constants, which in turn prevents // many mutual dependency problems between modules). Note: Action names must not contain any // spaces or tabs because within a script, those characters can be used in lieu of a delimiter // to separate the action-type-name from the first parameter. // Note about the sub-array: Since the parent array is global, it would be automatically // zero-filled if we didn't provide specific initialization. But since we do, I'm not sure // what value the unused elements in the NumericParams subarray will have. Therefore, it seems // safest to always terminate these subarrays with an explicit zero, below. // STEPS TO ADD A NEW COMMAND: // 1) Add an entry to the command enum in script.h. // 2) Add an entry to the below array (it's position here MUST exactly match that in the enum). // The first item is the command name, the second is the minimum number of parameters (e.g. // if you enter 3, the first 3 args are mandatory) and the third is the maximum number of // parameters (the user need not escape commas within the last parameter). // The subarray should indicate the param numbers that must be numeric (first param is numbered 1, // not zero). That subarray should be terminated with an explicit zero to be safe and // so that the compiler will complain if the sub-array size needs to be increased to // accommodate all the elements in the new sub-array, including room for its 0 terminator. // Note: If you use a value for MinParams than is greater than zero, remember than any params // beneath that threshold will also be required to be non-blank (i.e. user can't omit them even // if later, non-blank params are provided). UPDATE: For a parameter to recognize an expression // such as x+100, it must be listed in the sub-array as a pure numeric parameter. // 3) If the new command has any params that are output or input vars, change Line::ArgIsVar(). // 4) Add any desired load-time validation in Script::AddLine() in an syntax-checking section. // 5) Implement the command in Line::Perform() or Line::EvaluateCondition (if it's an IF). // If the command waits for anything (e.g. calls MsgSleep()), be sure to make a local // copy of any ARG values that are needed during the wait period, because if another hotkey // subroutine suspends the current one while its waiting, it could also overwrite the ARG // deref buffer with its own values. // v1.0.45 The following macro sets the high-bit for those commands that require overlap-checking of their // input/output variables during runtime (commands that don't have an output variable never need this byte // set, and runtime performance is improved even for them). Some of commands are given the high-bit even // though they might not strictly require it because rarity/performance/maintainability say it's best to do // so when in doubt. Search on "MaxParamsAu2WithHighBit" for more details. #define H |(char)0x80 Action g_act[] = { {_T(""), 0, 0, 0, NULL} // ACT_INVALID. // ACT_ASSIGN, ACT_ADD/SUB/MULT/DIV: Give them names for display purposes. // Note: Line::ToText() relies on the below names being the correct symbols for the operation: // 1st param is the target, 2nd (optional) is the value: , {_T("="), 1, 2, 2 H, NULL} // Omitting the second param sets the var to be empty. "H" (high-bit) is probably needed for those cases when PerformAssign() must call ExpandArgs() or similar. , {_T(":="), 1, 2, 2, {2, 0}} // Same, though param #2 is flagged as numeric so that expression detection is automatic. "H" (high-bit) doesn't appear to be needed even when ACT_ASSIGNEXPR calls AssignBinaryClip() because that AssignBinaryClip() checks for source==dest. // ACT_EXPRESSION, which is a stand-alone expression outside of any IF or assignment-command; // e.g. fn1(123, fn2(y)) or x&=3 // Its name should be "" so that Line::ToText() will properly display it. , {_T(""), 1, 1, 1, {1, 0}} , {_T("+="), 2, 3, 3, {2, 0}} , {_T("-="), 1, 3, 3, {2, 0}} // Subtraction (but not addition) allows 2nd to be blank due to 3rd param. , {_T("*="), 2, 2, 2, {2, 0}} , {_T("/="), 2, 2, 2, {2, 0}} // This command is never directly parsed, but we need to have it here as a translation // target for the old "repeat" command. This is because that command treats a zero // first-param as an infinite loop. Since that param can be a dereferenced variable, // there's no way to reliably translate each REPEAT command into a LOOP command at // load-time. Thus, we support both types of loops as actual commands that are // handled separately at runtime. , {_T("Repeat"), 0, 1, 1, {1, 0}} // Iteration Count: was mandatory in AutoIt2 but doesn't seem necessary here. , {_T("Else"), 0, 0, 0, NULL} , {_T("in"), 2, 2, 2, NULL}, {_T("not in"), 2, 2, 2, NULL} , {_T("contains"), 2, 2, 2, NULL}, {_T("not contains"), 2, 2, 2, NULL} // Very similar to "in" and "not in" , {_T("is"), 2, 2, 2, NULL}, {_T("is not"), 2, 2, 2, NULL} , {_T("between"), 1, 3, 3, NULL}, {_T("not between"), 1, 3, 3, NULL} // Min 1 to allow #2 and #3 to be the empty string. , {_T(""), 1, 1, 1, {1, 0}} // ACT_IFEXPR's name should be "" so that Line::ToText() will properly display it. // Comparison operators take 1 param (if they're being compared to blank) or 2. // For example, it's okay (though probably useless) to compare a string to the empty // string this way: "If var1 >=". Note: Line::ToText() relies on the below names: , {_T("="), 1, 2, 2, NULL}, {_T("<>"), 1, 2, 2, NULL}, {_T(">"), 1, 2, 2, NULL} , {_T(">="), 1, 2, 2, NULL}, {_T("<"), 1, 2, 2, NULL}, {_T("<="), 1, 2, 2, NULL} // For these, allow a minimum of zero, otherwise, the first param (WinTitle) would // be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that at least one of the four isn't blank. // Also, All the IFs must be physically adjacent to each other in this array // so that ACT_FIRST_IF and ACT_LAST_IF can be used to detect if a command is an IF: , {_T("IfWinExist"), 0, 4, 4, NULL}, {_T("IfWinNotExist"), 0, 4, 4, NULL} // Title, text, exclude-title, exclude-text // Passing zero params results in activating the LastUsed window: , {_T("IfWinActive"), 0, 4, 4, NULL}, {_T("IfWinNotActive"), 0, 4, 4, NULL} // same , {_T("IfInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfNotInString"), 2, 2, 2, NULL} // String var, search string , {_T("IfExist"), 1, 1, 1, NULL} // File or directory. , {_T("IfNotExist"), 1, 1, 1, NULL} // File or directory. // IfMsgBox must be physically adjacent to the other IFs in this array: , {_T("IfMsgBox"), 1, 1, 1, NULL} // MsgBox result (e.g. OK, YES, NO) , {_T("MsgBox"), 0, 4, 3, NULL} // Text (if only 1 param) or: Mode-flag, Title, Text, Timeout. , {_T("InputBox"), 1, 11, 11 H, {5, 6, 7, 8, 10, 0}} // Output var, title, prompt, hide-text (e.g. passwords), width, height, X, Y, Font (e.g. courier:8 maybe), Timeout, Default , {_T("SplashTextOn"), 0, 4, 4, {1, 2, 0}} // Width, height, title, text , {_T("SplashTextOff"), 0, 0, 0, NULL} , {_T("Progress"), 0, 6, 6, NULL} // Off|Percent|Options, SubText, MainText, Title, Font, FutureUse , {_T("SplashImage"), 0, 7, 7, NULL} // Off|ImageFile, |Options, SubText, MainText, Title, Font, FutureUse , {_T("ToolTip"), 0, 4, 4, {2, 3, 4, 0}} // Text, X, Y, ID. If Text is omitted, the Tooltip is turned off. , {_T("TrayTip"), 0, 4, 4, {3, 4, 0}} // Title, Text, Timeout, Options , {_T("Input"), 0, 4, 4 H, NULL} // OutputVar, Options, EndKeys, MatchList. , {_T("Transform"), 2, 4, 4 H, NULL} // output var, operation, value1, value2 , {_T("StringLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to extract , {_T("StringRight"), 3, 3, 3, {3, 0}} // same , {_T("StringMid"), 3, 5, 5, {3, 4, 0}} // Output Variable, Input Variable, Start char, Number of chars to extract, L , {_T("StringTrimLeft"), 3, 3, 3, {3, 0}} // output var, input var, number of chars to trim , {_T("StringTrimRight"), 3, 3, 3, {3, 0}} // same , {_T("StringLower"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringUpper"), 2, 3, 3, NULL} // output var, input var, T = Title Case , {_T("StringLen"), 2, 2, 2, NULL} // output var, input var , {_T("StringGetPos"), 3, 5, 3, {5, 0}} // Output Variable, Input Variable, Search Text, R or Right (from right), Offset , {_T("StringReplace"), 3, 5, 4, NULL} // Output Variable, Input Variable, Search String, Replace String, do-all. , {_T("StringSplit"), 2, 5, 5, NULL} // Output Array, Input Variable, Delimiter List (optional), Omit List, Future Use , {_T("SplitPath"), 1, 6, 6 H, NULL} // InputFilespec, OutName, OutDir, OutExt, OutNameNoExt, OutDrive , {_T("Sort"), 1, 2, 2, NULL} // OutputVar (it's also the input var), Options , {_T("EnvGet"), 2, 2, 2 H, NULL} // OutputVar, EnvVar , {_T("EnvSet"), 1, 2, 2, NULL} // EnvVar, Value , {_T("EnvUpdate"), 0, 0, 0, NULL} , {_T("RunAs"), 0, 3, 3, NULL} // user, pass, domain (0 params can be passed to disable the feature) , {_T("Run"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("RunWait"), 1, 4, 4 H, NULL} // TargetFile, Working Dir, WinShow-Mode/UseErrorLevel, OutputVarPID , {_T("URLDownloadToFile"), 2, 2, 2, NULL} // URL, save-as-filename , {_T("GetKeyState"), 2, 3, 3 H, NULL} // OutputVar, key name, mode (optional) P = Physical, T = Toggle , {_T("Send"), 1, 1, 1, NULL} // But that first param can validly be a deref that resolves to a blank param. , {_T("SendRaw"), 1, 1, 1, NULL} // , {_T("SendInput"), 1, 1, 1, NULL} // , {_T("SendPlay"), 1, 1, 1, NULL} // , {_T("SendEvent"), 1, 1, 1, NULL} // (due to rarity, there is no raw counterpart for this one) // For these, the "control" param can be blank. The window's first visible control will // be used. For this first one, allow a minimum of zero, otherwise, the first param (control) // would be considered mandatory-non-blank by default. It's easier to make all the params // optional and validate elsewhere that the 2nd one specifically isn't blank: , {_T("ControlSend"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlSendRaw"), 0, 6, 6, NULL} // Control, Chars-to-Send, std. 4 window params. , {_T("ControlClick"), 0, 8, 8, {5, 0}} // Control, WinTitle, WinText, WhichButton, ClickCount, Hold/Release, ExcludeTitle, ExcludeText , {_T("ControlMove"), 0, 9, 9, {2, 3, 4, 5, 0}} // Control, x, y, w, h, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("ControlGetPos"), 0, 9, 9 H, NULL} // Four optional output vars: xpos, ypos, width, height, control, std. 4 window params. , {_T("ControlFocus"), 0, 5, 5, NULL} // Control, std. 4 window params , {_T("ControlGetFocus"), 1, 5, 5 H, NULL} // OutputVar, std. 4 window params , {_T("ControlSetText"), 0, 6, 6, NULL} // Control, new text, std. 4 window params , {_T("ControlGetText"), 1, 6, 6 H, NULL} // Output-var, Control, std. 4 window params , {_T("Control"), 1, 7, 7, NULL} // Command, Value, Control, std. 4 window params , {_T("ControlGet"), 2, 8, 8 H, NULL} // Output-var, Command, Value, Control, std. 4 window params , {_T("SendMode"), 1, 1, 1, NULL} , {_T("SendLevel"), 1, 1, 1, {1, 0}} , {_T("CoordMode"), 1, 2, 2, NULL} // Attribute, screen|relative , {_T("SetDefaultMouseSpeed"), 1, 1, 1, {1, 0}} // speed (numeric) , {_T("Click"), 0, 1, 1, NULL} // Flex-list of options. , {_T("MouseMove"), 2, 4, 4, {1, 2, 3, 0}} // x, y, speed, option , {_T("MouseClick"), 0, 7, 7, {2, 3, 4, 5, 0}} // which-button, x, y, ClickCount, speed, d=hold-down/u=release, Relative , {_T("MouseClickDrag"), 1, 7, 7, {2, 3, 4, 5, 6, 0}} // which-button, x1, y1, x2, y2, speed, Relative , {_T("MouseGetPos"), 0, 5, 5 H, {5, 0}} // 4 optional output vars: xpos, ypos, WindowID, ControlName. Finally: Mode. MinParams must be 0. , {_T("StatusBarGetText"), 1, 6, 6 H, {2, 0}} // Output-var, part# (numeric), std. 4 window params , {_T("StatusBarWait"), 0, 8, 8, {2, 3, 6, 0}} // Wait-text(blank ok),seconds,part#,title,text,interval,exclude-title,exclude-text , {_T("ClipWait"), 0, 2, 2, {1, 2, 0}} // Seconds-to-wait (0 = 500ms), 1|0: Wait for any format, not just text/files , {_T("KeyWait"), 1, 2, 2, NULL} // KeyName, Options , {_T("Sleep"), 1, 1, 1, {1, 0}} // Sleep time in ms (numeric) , {_T("Random"), 0, 3, 3, {2, 3, 0}} // Output var, Min, Max (Note: MinParams is 1 so that param2 can be blank). , {_T("Goto"), 1, 1, 1, NULL} , {_T("Gosub"), 1, 1, 1, NULL} // Label (or dereference that resolves to a label). , {_T("OnExit"), 0, 2, 2, NULL} // Optional label, future use (since labels are allowed to contain commas) , {_T("Hotkey"), 1, 3, 3, NULL} // Mod+Keys, Label/Action (blank to avoid changing curr. label), Options , {_T("SetTimer"), 0, 3, 3, {3, 0}} // Label (or dereference that resolves to a label), period (or ON/OFF), Priority , {_T("Critical"), 0, 1, 1, NULL} // On|Off , {_T("Thread"), 1, 3, 3, {2, 3, 0}} // Command, value1 (can be blank for interrupt), value2 , {_T("Return"), 0, 1, 1, {1, 0}} , {_T("Exit"), 0, 1, 1, {1, 0}} // ExitCode , {_T("Loop"), 0, 4, 4, NULL} // Iteration Count or FilePattern or root key name [,subkey name], FileLoopMode, Recurse? (custom validation for these last two) , {_T("For"), 1, 3, 3, {3, 0}} // For var [,var] in expression , {_T("While"), 1, 1, 1, {1, 0}} // LoopCondition. v1.0.48: Lexikos: Added g_act entry for ACT_WHILE. , {_T("Until"), 1, 1, 1, {1, 0}} // Until expression (follows a Loop) , {_T("Break"), 0, 1, 1, NULL}, {_T("Continue"), 0, 1, 1, NULL} , {_T("Try"), 0, 0, 0, NULL} , {_T("Catch"), 0, 1, 0, NULL} // fincs: seems best to allow catch without a parameter , {_T("Throw"), 0, 1, 1, {1, 0}} , {_T("{"), 0, 0, 0, NULL}, {_T("}"), 0, 0, 0, NULL} , {_T("WinActivate"), 0, 4, 2, NULL} // Passing zero params results in activating the LastUsed window. , {_T("WinActivateBottom"), 0, 4, 4, NULL} // Min. 0 so that 1st params can be blank and later ones not blank. // These all use Title, Text, Timeout (in seconds not ms), Exclude-title, Exclude-text. // See above for why zero is the minimum number of params for each: , {_T("WinWait"), 0, 5, 5, {3, 0}}, {_T("WinWaitClose"), 0, 5, 5, {3, 0}} , {_T("WinWaitActive"), 0, 5, 5, {3, 0}}, {_T("WinWaitNotActive"), 0, 5, 5, {3, 0}} , {_T("WinMinimize"), 0, 4, 2, NULL}, {_T("WinMaximize"), 0, 4, 2, NULL}, {_T("WinRestore"), 0, 4, 2, NULL} // std. 4 params , {_T("WinHide"), 0, 4, 2, NULL}, {_T("WinShow"), 0, 4, 2, NULL} // std. 4 params , {_T("WinMinimizeAll"), 0, 0, 0, NULL}, {_T("WinMinimizeAllUndo"), 0, 0, 0, NULL} , {_T("WinClose"), 0, 5, 2, {3, 0}} // title, text, time-to-wait-for-close (0 = 500ms), exclude title/text , {_T("WinKill"), 0, 5, 2, {3, 0}} // same as WinClose. , {_T("WinMove"), 0, 8, 8, {1, 2, 3, 4, 5, 6, 0}} // title, text, xpos, ypos, width, height, exclude-title, exclude_text // Note for WinMove: title/text are marked as numeric because in two-param mode, they are the X/Y params. // This helps speed up loading expression-detection. Also, xpos/ypos/width/height can be the string "default", // but that is explicitly checked for, even though it is required it to be numeric in the definition here. , {_T("WinMenuSelectItem"), 0, 11, 11, NULL} // WinTitle, WinText, Menu name, 6 optional sub-menu names, ExcludeTitle/Text , {_T("Process"), 1, 3, 3, NULL} // Sub-cmd, PID/name, Param3 (use minimum of 1 param so that 2nd can be blank) , {_T("WinSet"), 1, 6, 6, NULL} // attribute, setting, title, text, exclude-title, exclude-text // WinSetTitle: Allow a minimum of zero params so that title isn't forced to be non-blank. // Also, if the user passes only one param, the title of the "last used" window will be // set to the string in the first param: , {_T("WinSetTitle"), 0, 5, 3, NULL} // title, text, newtitle, exclude-title, exclude-text , {_T("WinGetTitle"), 1, 5, 3 H, NULL} // Output-var, std. 4 window params , {_T("WinGetClass"), 1, 5, 5 H, NULL} // Output-var, std. 4 window params , {_T("WinGet"), 1, 6, 6 H, NULL} // Output-var/array, cmd (if omitted, defaults to ID), std. 4 window params , {_T("WinGetPos"), 0, 8, 8 H, NULL} // Four optional output vars: xpos, ypos, width, height. Std. 4 window params. , {_T("WinGetText"), 1, 5, 5 H, NULL} // Output var, std 4 window params. , {_T("SysGet"), 2, 4, 4 H, NULL} // Output-var/array, sub-cmd or sys-metrics-number, input-value1, future-use , {_T("PostMessage"), 1, 8, 8, {1, 2, 3, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText , {_T("SendMessage"), 1, 9, 9, {1, 2, 3, 9, 0}} // msg, wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout , {_T("PixelGetColor"), 3, 4, 4 H, {2, 3, 0}} // OutputVar, X-coord, Y-coord [, RGB] , {_T("PixelSearch"), 0, 9, 9 H, {3, 4, 5, 6, 7, 8, 0}} // OutputX, OutputY, left, top, right, bottom, Color, Variation [, RGB] , {_T("ImageSearch"), 0, 7, 7 H, {3, 4, 5, 6, 0}} // OutputX, OutputY, left, top, right, bottom, ImageFile // NOTE FOR THE ABOVE: 0 min args so that the output vars can be optional. // See above for why minimum is 1 vs. 2: , {_T("GroupAdd"), 1, 6, 6, NULL} // Group name, WinTitle, WinText, Label, exclude-title/text , {_T("GroupActivate"), 1, 2, 2, NULL} , {_T("GroupDeactivate"), 1, 2, 2, NULL} , {_T("GroupClose"), 1, 2, 2, NULL} , {_T("DriveSpaceFree"), 2, 2, 2 H, NULL} // Output-var, path (e.g. c:\) , {_T("Drive"), 1, 3, 3, NULL} // Sub-command, Value1 (can be blank for Eject), Value2 , {_T("DriveGet"), 0, 3, 3 H, NULL} // Output-var (optional in at least one case), Command, Value , {_T("SoundGet"), 1, 4, 4 H, {4, 0}} // OutputVar, ComponentType (default=master), ControlType (default=vol), Mixer/Device Number , {_T("SoundSet"), 1, 4, 4, {1, 4, 0}} // Volume percent-level (0-100), ComponentType, ControlType (default=vol), Mixer/Device Number , {_T("SoundGetWaveVolume"), 1, 2, 2 H, {2, 0}} // OutputVar, Mixer/Device Number , {_T("SoundSetWaveVolume"), 1, 2, 2, {1, 2, 0}} // Volume percent-level (0-100), Device Number (1 is the first) , {_T("SoundBeep"), 0, 2, 2, {1, 2, 0}} // Frequency, Duration. , {_T("SoundPlay"), 1, 2, 2, NULL} // Filename [, wait] , {_T("FileAppend"), 0, 3, 3, NULL} // text, filename (which can be omitted in a read-file loop). Update: Text can be omitted too, to create an empty file or alter the timestamp of an existing file. , {_T("FileRead"), 2, 2, 2 H, NULL} // Output variable, filename , {_T("FileReadLine"), 3, 3, 3 H, {3, 0}} // Output variable, filename, line-number , {_T("FileDelete"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycle"), 1, 1, 1, NULL} // filename or pattern , {_T("FileRecycleEmpty"), 0, 1, 1, NULL} // optional drive letter (all bins will be emptied if absent. , {_T("FileInstall"), 2, 3, 3, {3, 0}} // source, dest, flag (1/0, where 1=overwrite) , {_T("FileCopy"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMove"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileCopyDir"), 2, 3, 3, {3, 0}} // source, dest, flag , {_T("FileMoveDir"), 2, 3, 3, NULL} // source, dest, flag (which can be non-numeric in this case) , {_T("FileCreateDir"), 1, 1, 1, NULL} // dir name , {_T("FileRemoveDir"), 1, 2, 1, {2, 0}} // dir name, flag , {_T("FileGetAttrib"), 1, 2, 2 H, NULL} // OutputVar, Filespec (if blank, uses loop's current file) , {_T("FileSetAttrib"), 1, 4, 4, {3, 4, 0}} // Attribute(s), FilePattern, OperateOnFolders?, Recurse? (custom validation for these last two) , {_T("FileGetTime"), 1, 3, 3 H, NULL} // OutputVar, Filespec, WhichTime (modified/created/accessed) , {_T("FileSetTime"), 0, 5, 5, {1, 4, 5, 0}} // datetime (YYYYMMDDHH24MISS), FilePattern, WhichTime, OperateOnFolders?, Recurse? , {_T("FileGetSize"), 1, 3, 3 H, NULL} // OutputVar, Filespec, B|K|M (bytes, kb, or mb) , {_T("FileGetVersion"), 1, 2, 2 H, NULL} // OutputVar, Filespec , {_T("SetWorkingDir"), 1, 1, 1, NULL} // New path , {_T("FileSelectFile"), 1, 5, 3 H, NULL} // output var, options, working dir, greeting, filter , {_T("FileSelectFolder"), 1, 4, 4 H, {3, 0}} // output var, root directory, options, greeting , {_T("FileGetShortcut"), 1, 8, 8 H, NULL} // Filespec, OutTarget, OutDir, OutArg, OutDescrip, OutIcon, OutIconIndex, OutShowState. , {_T("FileCreateShortcut"), 2, 9, 9, {8, 9, 0}} // file, lnk [, workdir, args, desc, icon, hotkey, icon_number, run_state] , {_T("IniRead"), 2, 5, 4 H, NULL} // OutputVar, Filespec, Section, Key, Default (value to return if key not found) , {_T("IniWrite"), 3, 4, 4, NULL} // Value, Filespec, Section, Key , {_T("IniDelete"), 2, 3, 3, NULL} // Filespec, Section, Key // These require so few parameters due to registry loops, which provide the missing parameter values // automatically. In addition, RegRead can't require more than 1 param since the 2nd param is // an option/obsolete parameter: , {_T("RegRead"), 1, 5, 5 H, NULL} // output var, (ValueType [optional]), RegKey, RegSubkey, ValueName , {_T("RegWrite"), 0, 5, 5, NULL} // ValueType, RegKey, RegSubKey, ValueName, Value (set to blank if omitted?) , {_T("RegDelete"), 0, 3, 3, NULL} // RegKey, RegSubKey, ValueName , {_T("OutputDebug"), 1, 1, 1, NULL} , {_T("SetKeyDelay"), 0, 3, 3, {1, 2, 0}} // Delay in ms (numeric, negative allowed), PressDuration [, Play] , {_T("SetMouseDelay"), 1, 2, 2, {1, 0}} // Delay in ms (numeric, negative allowed) [, Play] , {_T("SetWinDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetControlDelay"), 1, 1, 1, {1, 0}} // Delay in ms (numeric, negative allowed) , {_T("SetBatchLines"), 1, 1, 1, NULL} // Can be non-numeric, such as 15ms, or a number (to indicate line count). , {_T("SetTitleMatchMode"), 1, 1, 1, NULL} // Allowed values: 1, 2, slow, fast , {_T("SetFormat"), 2, 2, 2, NULL} // Float|Integer, FormatString (for float) or H|D (for int) diff --git a/source/globaldata.h b/source/globaldata.h index 8d5fc50..0c45de0 100644 --- a/source/globaldata.h +++ b/source/globaldata.h @@ -1,349 +1,351 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 and g_ErrorLevel #include "os_version.h" // For the global OS_Version object #include "Debugger.h" extern HRSRC g_hResource; extern HINSTANCE g_hInstance; extern DWORD g_MainThreadID; extern DWORD g_HookThreadID; +extern ATOM g_ClassRegistered; +extern ATOM g_ClassSplashRegistered; 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; #ifndef MINIDLL extern HWND g_hWndSplash; // The SplashText window. extern HFONT g_hFontSplash; #endif extern HACCEL g_hAccelTable; // Accelerator table for main menu shortcut keys. 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. #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_HookReceiptOfLControlMeansAltGr; extern DWORD g_IgnoreNextLControlDown; extern DWORD g_IgnoreNextLControlUp; extern BYTE g_MenuMaskKey; // L38: See #MenuMaskKey. // 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_Warn_UseUnsetLocal; extern WarnMode g_Warn_UseUnsetGlobal; extern WarnMode g_Warn_UseEnv; extern WarnMode g_Warn_LocalSameAsGlobal; #ifndef MINIDLL extern SingleInstanceType g_AllowOnlyOneInstance; #endif extern bool g_persistent; #ifndef MINIDLL extern bool g_NoTrayIcon; #endif #ifdef AUTOHOTKEYSC extern bool g_AllowMainWindow; #endif extern bool g_AllowSameLineComments; extern bool g_DeferMessagesForUnderlyingPump; extern bool g_MainTimerExists; extern bool g_AutoExecTimerExists; #ifndef MINIDLL extern bool g_InputTimerExists; #endif extern bool g_DerefTimerExists; extern bool g_SoundWasPlayed; #ifndef MINIDLL extern bool g_IsSuspended; #endif extern BOOL g_WriteCacheDisabledInt64; extern BOOL g_WriteCacheDisabledDouble; extern BOOL g_NoEnv; extern BOOL g_AllowInterruption; extern int g_nLayersNeedingTimer; extern int g_nThreads; extern int g_nPausedThreads; #ifndef MINIDLL extern int g_MaxHistoryKeys; #endif extern VarSizeType g_MaxVarCapacity; #ifndef MINIDLL extern UCHAR g_MaxThreadsPerHotkey; #endif extern int g_MaxThreadsTotal; #ifndef MINIDLL extern int g_MaxHotkeysPerInterval; extern int g_HotkeyThrottleInterval; #endif extern bool g_MaxThreadsBuffer; extern SendLevelType g_InputLevel; #ifndef MINIDLL extern HotCriterionType g_HotCriterion; extern LPTSTR g_HotWinTitle; extern LPTSTR g_HotWinText; extern HotkeyCriterion *g_FirstHotCriterion, *g_LastHotCriterion; // Global variables for #if (expression). See globaldata.cpp for comments. extern int g_HotExprIndex; extern Line **g_HotExprLines; extern int g_HotExprLineCount; extern int g_HotExprLineCountMax; extern UINT g_HotExprTimeout; extern HWND g_HotExprLFW; extern MenuTypeType g_MenuIsVisible; #endif extern int g_nMessageBoxes; #ifndef MINIDLL extern int g_nInputBoxes; extern int g_nFileDialogs; extern int g_nFolderDialogs; extern InputBoxType g_InputBox[MAX_INPUTBOXES]; extern SplashType g_Progress[MAX_PROGRESS_WINDOWS]; extern SplashType g_SplashImage[MAX_SPLASHIMAGE_WINDOWS]; extern GuiType **g_gui; extern int g_guiCount, g_guiCountMax; #endif extern HWND g_hWndToolTip[MAX_TOOLTIPS]; extern MsgMonitorStruct *g_MsgMonitor; // An array to be allocated upon first use (if any). extern int g_MsgMonitorCount; extern UCHAR g_SortCaseSensitive; extern bool g_SortNumeric; extern bool g_SortReverse; extern int g_SortColumnOffset; extern Func *g_SortFunc; extern TCHAR g_delimiter; extern TCHAR g_DerefChar; extern TCHAR g_EscapeChar; #ifndef MINIDLL // 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 bool g_HSCaseSensitive; extern bool g_HSConformToCase; extern bool g_HSDoBackspace; extern bool g_HSOmitEndChar; extern bool g_HSSendRaw; extern bool g_HSEndCharRequired; extern bool g_HSDetectWhenInsideWord; extern bool g_HSDoReset; extern bool g_HSResetUponMouseClick; extern TCHAR g_EndChars[HS_MAX_END_CHARS + 1]; #endif // Global objects: extern Var *g_ErrorLevel; #ifndef MINIDLL extern input_type g_input; #endif EXTERN_SCRIPT; EXTERN_CLIPBOARD; EXTERN_OSVER; #ifndef MINIDLL extern int g_IconTray; extern int g_IconTraySuspend; #endif extern DWORD g_OriginalTimeout; EXTERN_G; extern global_struct g_default, *g_array; extern TCHAR g_WorkingDir[MAX_PATH]; // Explicit size needed here in .h file for use with sizeof(). extern LPTSTR g_WorkingDirOrig; extern bool g_ContinuationLTrim; 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; #ifndef MINIDLL extern KeyHistoryItem *g_KeyHistory; extern int g_KeyHistoryNext; extern DWORD g_HistoryTickNow; extern DWORD g_HistoryTickPrev; extern HWND g_HistoryHwndPrev; #endif extern DWORD g_TimeLastInputPhysical; #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE extern bool g_KeyHistoryToFile; #endif #endif // MINIDLL // 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. #define SET_AUTOEXEC_TIMER(aTimeoutValue) \ {\ g->AllowThreadToBeInterrupted = false;\ g->ThreadStartTime = GetTickCount();\ g->UninterruptibleDuration = aTimeoutValue;\ if (!g_AutoExecTimerExists)\ g_AutoExecTimerExists = SetTimer(g_hWnd, TIMER_ID_AUTOEXEC, aTimeoutValue, AutoExecSectionTimeout);\ } // v1.0.39 for above: Removed the call to ExitApp() upon failure. See SET_MAIN_TIMER for details. #ifndef MINIDLL #define SET_INPUT_TIMER(aTimeoutValue) \ if (!g_InputTimerExists)\ g_InputTimerExists = SetTimer(g_hWnd, TIMER_ID_INPUT, aTimeoutValue, InputTimeout); #endif // 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; // See above comment about g->AllowThreadToBeInterrupted. #define KILL_AUTOEXEC_TIMER \ {\ if (g_AutoExecTimerExists && KillTimer(g_hWnd, TIMER_ID_AUTOEXEC))\ g_AutoExecTimerExists = false;\ } #ifndef MINIDLL #define KILL_INPUT_TIMER \ if (g_InputTimerExists && KillTimer(g_hWnd, TIMER_ID_INPUT))\ g_InputTimerExists = false; #endif #define KILL_DEREF_TIMER \ if (g_DerefTimerExists && KillTimer(g_hWnd, TIMER_ID_DEREF))\ g_DerefTimerExists = false; #endif diff --git a/source/script.cpp b/source/script.cpp index bbd036a..1fc12a3 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -63,1039 +63,1039 @@ Script::Script() #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFunc(NULL), mFuncCount(0), mFuncCountMax(0) , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mClassObjectCount(0) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mIsAutoIt2(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (g_ActionCount != ACT_COUNT) // This enum value only exists in debug mode. ScriptError(_T("DEBUG: g_act and enum_act are out of sync.")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: while (g_guiCount) GuiType::Destroy(*g_gui[g_guiCount-1]); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. if (MyRemoveClipboardListener && MyAddClipboardListener) MyRemoveClipboardListener(g_hWnd); // MyAddClipboardListener was used. else ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // SetClipboardViewer was used. // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { /* //ExprTokenType aResultToken; static ExprTokenType **aParam = (ExprTokenType **)SimpleHeap::Malloc(sizeof(__int64));; ExprTokenType aThisParam[1]; aThisParam[0].symbol = SYM_STRING; aThisParam[0].marker = _T(""); aParam[0] = aThisParam; int aParamCount = 0; BIF_DynaCall(aThisParam[0], aParam, aParamCount); */ // Disconnect debugger if (!g_DebuggerHost.IsEmpty()) { g_DebuggerHost.Empty(); g_Debugger.Disconnect(); } // L31: Release objects stored in variables, where possible. int v, i; g_script.mIsReadyToExecute = false; for (v = 0; v < mVarCount; ++v) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN || mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; mVar[v]->ConvertToNonAliasIfNecessary(); if (mVar[v]->IsObject()) mVar[v]->ReleaseObject(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; ++v) { mLazyVar[v]->ConvertToNonAliasIfNecessary(); mLazyVar[v]->Free(); } for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) { f.mVar[v]->ConvertToNonAliasIfNecessary(); f.mVar[v]->Free(); } for (v = 0; v < f.mLazyVarCount; ++v) { f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); f.mLazyVar[v]->Free(); } delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel; label != NULL;label = label->mNextLabel) { Label *nextLabel = label->mNextLabel; label->mJumpToLine = NULL; label->mName = _T(""); label->mPrevLabel = NULL; } for (Line *line = g_script.mLastLine; line;) { Line *nextLine = line->mPrevLine; delete line; line = nextLine; } mFuncCount = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; #ifndef MINIDLL mFirstMenu = NULL; #endif mFirstTimer = NULL; mIsReadyToExecute = false; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; for(i=1;Line::sSourceFileCount>i;i++) // HotKeyIt: first include file must not be deleted free(Line::sSourceFile[i]); Line::sSourceFileCount = 0; //free(Line::sSourceFile); // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } #ifndef MINIDLL AddRemoveHooks(0); Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif Script::~Script(); global_clear_state(*g); //free(g_Debugger.mStack.mBottom); #ifndef MINIDLL free(g_input.match); #endif free(g_MsgMonitor); } #endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else TCHAR def_buf[MAX_PATH + 1], exe_buf[MAX_PATH + 1]; if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { #ifdef STANDALONE BIV_AhkPath(aScriptFilename,_T("")); #else // Since no script-file was specified on the command line, use the default name. // For portability, first check if there's an <EXENAME>.ahk file in the current directory. LPTSTR suffix, dot; GetModuleFileName(NULL, exe_buf, _countof(exe_buf)); if ( (suffix = _tcsrchr(exe_buf, '\\')) // Find name part of path. && (dot = _tcsrchr(suffix, '.')) // Find extension part of name. && dot - exe_buf + 5 < _countof(exe_buf) ) // Enough space in buffer? { _tcscpy(dot, _T(".ahk")); } else // Very unlikely. return FAIL; aScriptFilename = exe_buf; // Use the entire path, including the exe's directory. if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { aScriptFilename = def_buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length + _tcslen(suffix) + 1 > _countof(def_buf)) return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, suffix); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } #endif // In case the script is a relative filespec (relative to current working dir): if (g_hResource || (hInstance != NULL && aIsText)) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. size_t filename_length = _tcslen(filename_marker); #ifndef _USRDLL if ( mIsAutoIt2 = (filename_length >= 4 && !_tcsicmp(filename_marker + filename_length - 4, EXT_AUTOIT2)) ) { // Set the old/AutoIt2 defaults for maximum safety and compatibility. // Standalone EXEs (compiled scripts) are always considered to be non-AutoIt2 (otherwise, // the user should probably be using the AutoIt2 compiler). g_AllowSameLineComments = false; g_EscapeChar = '\\'; g.TitleFindFast = true; // In case the normal default is false. g.DetectHiddenText = false; // Make the mouse fast like AutoIt2, but not quite insta-move. 2 is expected to be more // reliable than 1 since the AutoIt author said that values less than 2 might cause the // drag to fail (perhaps just for specific apps, such as games): g.DefaultMouseSpeed = 2; g.KeyDelay = 20; g.WinDelay = 500; g.LinesPerCycle = 1; g.IntervalBeforeRest = -1; // i.e. this method is disabled by default for AutoIt2 scripts. // Reduce max params so that any non escaped delimiters the user may be using literally // in "window text" will still be considered literal, rather than as delimiters for // args that are not supported by AutoIt2, such as exclude-title, exclude-text, MsgBox // timeout, etc. Note: Don't need to change IfWinExist and such because those already // have special handling to recognize whether exclude-title is really a valid command // instead (e.g. IfWinExist, title, text, Gosub, something). // NOTE: DO NOT ADD the IfWin command series to this section, since there is special handling // for parsing those commands to figure out whether they're being used in the old AutoIt2 // style or the new Exclude Title/Text mode. // v1.0.40.02: The following is no longer done because a different mechanism is required now // that the ARGn macros do not check whether mArgc is too small and substitute an empty string // (instead, there is a loop in ExpandArgs that puts an empty string in each sArgDeref entry // for which the script omitted a parameter [and that loop relies on MaxParams being absolutely // accurate rather than conditional upon whether the script is of type ".aut"]). //g_act[ACT_FILESELECTFILE].MaxParams -= 2; //g_act[ACT_FILEREMOVEDIR].MaxParams -= 1; //g_act[ACT_MSGBOX].MaxParams -= 1; //g_act[ACT_INIREAD].MaxParams -= 1; //g_act[ACT_STRINGREPLACE].MaxParams -= 1; //g_act[ACT_STRINGGETPOS].MaxParams -= 2; //g_act[ACT_WINCLOSE].MaxParams -= 3; // -3 for these two, -2 for the others. //g_act[ACT_WINKILL].MaxParams -= 3; //g_act[ACT_WINACTIVATE].MaxParams -= 2; //g_act[ACT_WINMINIMIZE].MaxParams -= 2; //g_act[ACT_WINMAXIMIZE].MaxParams -= 2; //g_act[ACT_WINRESTORE].MaxParams -= 2; //g_act[ACT_WINHIDE].MaxParams -= 2; //g_act[ACT_WINSHOW].MaxParams -= 2; //g_act[ACT_WINSETTITLE].MaxParams -= 2; //g_act[ACT_WINGETTITLE].MaxParams -= 2; } #endif if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class - RegisterClassEx(&wc); + g_ClassRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class - RegisterClassEx(&wc); + g_ClassSplashRegistered = RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if ( !(g_array = (global_struct *)malloc((g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "background thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT); return OK; } #ifndef MINIDLL ResultType Script::Edit() { #ifdef AUTOHOTKEYSC return OK; // Do nothing. #else // This is here in case a compiled script ever uses the Edit command. Since the "Edit This // Script" menu item is not available for compiled scripts, it can't be called from there. TitleMatchModes old_mode = g->TitleMatchMode; g->TitleMatchMode = FIND_ANYWHERE; HWND hwnd = WinExist(*g, mFileName, _T(""), mMainWindowTitle, _T("")); // Exclude our own main window. g->TitleMatchMode = old_mode; if (hwnd) { TCHAR class_name[32]; GetClassName(hwnd, class_name, _countof(class_name)); if (!_tcscmp(class_name, _T("#32770")) || !_tcsnicmp(class_name, _T("AutoHotkey"), 10)) // MessageBox(), InputBox(), FileSelectFile(), or GUI/script-owned window. hwnd = NULL; // Exclude it from consideration. } if (hwnd) // File appears to already be open for editing, so use the current window. SetForegroundWindowEx(hwnd); else { TCHAR buf[MAX_PATH * 2]; // Enclose in double quotes anything that might contain spaces since the CreateProcess() // method, which is attempted first, is more likely to succeed. This is because it uses // the command line method of creating the process, with everything all lumped together: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) // Since this didn't work, try notepad. { // v1.0.40.06: Try to open .ini files first with their associated editor rather than trying the // "edit" verb on them: LPTSTR file_ext; if ( !(file_ext = _tcsrchr(mFileName, '.')) || _tcsicmp(file_ext, _T(".ini")) || !ActionExec(_T("open"), buf, mFileDir, false) ) // Relies on short-circuit boolean order. { // Even though notepad properly handles filenames with spaces in them under WinXP, // even without double quotes around them, it seems safer and more correct to always // enclose the filename in double quotes for maximum compatibility with all OSes: if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) MsgBox(_T("Could not open script.")); // Short message since so rare. } } } return OK; #endif } #endif // MINIDLL ResultType Script::Reload(bool aDisplayErrors) { // The new instance we're about to start will tell our process to stop, or it will display // a syntax error or some other error, in which case our process will still be running: #ifdef _USRDLL reloadDll(); return EARLY_RETURN; #else #ifdef AUTOHOTKEYSC // This is here in case a compiled script ever uses the Reload command. Since the "Reload This // Script" menu item is not available for compiled scripts, it can't be called from there. return g_script.ActionExec(mOurEXE, _T("/restart"), g_WorkingDirOrig, aDisplayErrors); #else TCHAR arg_string[MAX_PATH + 512]; sntprintf(arg_string, _countof(arg_string), _T("/restart \"%s\""), mFileSpec); return g_script.ActionExec(mOurEXE, arg_string, g_WorkingDirOrig, aDisplayErrors); #endif // AUTOHOTKEYSC #endif // _USRDLL } ResultType Script::ExitApp(ExitReasons aExitReason, LPTSTR aBuf, int aExitCode) // Normal exit (if aBuf is NULL), or a way to exit immediately on error (which is mostly // for times when it would be unsafe to call MsgBox() due to the possibility that it would // make the situation even worse). { mExitReason = aExitReason; bool terminate_afterward = aBuf && !*aBuf; if (aBuf && *aBuf) { TCHAR buf[1024]; // No more than size-1 chars will be written and string will be terminated: sntprintf(buf, _countof(buf), _T("Critical Error: %s\n\n") WILL_EXIT, aBuf); // To avoid chance of more errors, don't use MsgBox(): MessageBox(g_hWnd, buf, g_script.mFileSpec, MB_OK | MB_SETFOREGROUND | MB_APPLMODAL); TerminateApp(aExitReason, CRITICAL_ERROR); // Only after the above. } // Otherwise, it's not a critical error. Note that currently, mOnExitLabel can only be // non-NULL if the script is in a runnable state (since registering an OnExit label requires // that a script command has executed to do it). If this ever changes, the !mIsReadyToExecute // condition should be added to the below if statement: static bool sExitLabelIsRunning = false; if (!mOnExitLabel || sExitLabelIsRunning) // || !mIsReadyToExecute { // In the case of sExitLabelIsRunning == true: // There is another instance of this function beneath us on the stack. Since we have // been called, this is a true exit condition and we exit immediately. // MUST NOT create a new thread when sExitLabelIsRunning because g_array allows only one // extra thread for ExitApp() (which allows it to run even when MAX_THREADS_EMERGENCY has // been reached). See TOTAL_ADDITIONAL_THREADS. g_AllowInterruption = FALSE; // In case TerminateApp releases objects and indirectly causes g->IsPaused = false; // more script to be executed. TerminateApp(aExitReason, aExitCode); } // Otherwise, the script contains the special RunOnExit label that we will run here instead // of exiting. And since it does, we know that the script is in a ready-to-execute state // because that is the only way an OnExit label could have been defined in the first place. // Usually, the RunOnExit subroutine will contain an Exit or ExitApp statement // which results in a recursive call to this function, but this is not required (e.g. the // Exit subroutine could display an "Are you sure?" prompt, and if the user chooses "No", // the Exit sequence can be aborted by simply not calling ExitApp and letting the thread // we create below end normally). // Next, save the current state of the globals so that they can be restored just prior // to returning to our caller: TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); // Save caller's errorlevel. InitNewThread(0, true, true, ACT_INVALID); // Uninterruptibility is handled below. Since this special thread should always run, no checking of g_MaxThreadsTotal is done before calling this. // Turn on uninterruptibility to forbid any hotkeys, timers, or user defined menu items // to interrupt. This is mainly done for peace-of-mind (since possible interactions due to // interruptions have not been studied) and the fact that this most users would not want this // subroutine to be interruptible (it usually runs quickly anyway). Another reason to make // it non-interruptible is that some OnExit subroutines might destruct things used by the // script's hotkeys/timers/menu items, and activating these items during the deconstruction // would not be safe. Finally, if a logoff or shutdown is occurring, it seems best to prevent // timed subroutines from running -- which might take too much time and prevent the exit from // occurring in a timely fashion. An option can be added via the FutureUse param to make it // interruptible if there is ever a demand for that. // UPDATE: g_AllowInterruption is now used instead of g->AllowThreadToBeInterrupted for two reasons: // 1) It avoids the need to do "int mUninterruptedLineCountMax_prev = g_script.mUninterruptedLineCountMax;" // (Disable this item so that ExecUntil() won't automatically make our new thread uninterruptible // after it has executed a certain number of lines). // 2) Mostly obsolete: If the thread we're interrupting is uninterruptible, the uninterruptible timer // might be currently pending. When it fires, it would make the OnExit subroutine interruptible // rather than the underlying subroutine. The above fixes the first part of that problem. // The 2nd part is fixed by reinstating the timer when the uninterruptible thread is resumed. // This special handling is only necessary here -- not in other places where new threads are // created -- because OnExit is the only type of thread that can interrupt an uninterruptible // thread. BOOL g_AllowInterruption_prev = g_AllowInterruption; // Save current setting. g_AllowInterruption = FALSE; // Mark the thread just created above as permanently uninterruptible (i.e. until it finishes and is destroyed). sExitLabelIsRunning = true; DEBUGGER_STACK_PUSH(mOnExitLabel->mJumpToLine, mOnExitLabel->mName) if (mOnExitLabel->Execute() == FAIL) { // If the subroutine encounters a failure condition such as a runtime error, exit immediately. // Otherwise, there will be no way to exit the script if the subroutine fails on each attempt. TerminateApp(aExitReason, aExitCode); } DEBUGGER_STACK_POP() sExitLabelIsRunning = false; // In case the user wanted the thread to end normally (see above). if (terminate_afterward) diff --git a/source/script_gui.cpp b/source/script_gui.cpp index a98c556..0edc0c5 100644 --- a/source/script_gui.cpp +++ b/source/script_gui.cpp @@ -1272,1029 +1272,1033 @@ ResultType Line::GuiControl(LPTSTR aCommand, LPTSTR aControlID, LPTSTR aParam3) selection_index = gui.FindTabIndexByName(control, aParam3); // Returns -1 on failure. else selection_index = ATOI(aParam3) - 1; if (selection_index < 0 || selection_index > MAX_TABS_PER_CONTROL - 1) goto error; int previous_selection_index = TabCtrl_GetCurSel(control.hwnd); if (!extra_actions || (GetWindowLong(control.hwnd, GWL_STYLE) & TCS_BUTTONS)) { if (TabCtrl_SetCurSel(control.hwnd, selection_index) == -1) goto error; // In this case but not the "else" below, must update the tab to show the proper controls: if (previous_selection_index != selection_index) gui.ControlUpdateCurrentTab(control, extra_actions > 0); // And set focus if the more forceful extra_actions was done. } else // There is an extra_action and it's not TCS_BUTTONS, so extra_action is possible via TabCtrl_SetCurFocus. { TabCtrl_SetCurFocus(control.hwnd, selection_index); // No return value, so check for success below. if (TabCtrl_GetCurSel(control.hwnd) != selection_index) goto error; } goto return_the_result; } // Otherwise, it's not a tab control, but a ListBox/DropDownList/Combo or other control: if (*aParam3 == gui.mDelimiter && control.type != GUI_CONTROL_TAB) // Second extra action. { ++aParam3; // Omit this pipe char from further consideration below. ++extra_actions; } if (guicontrol_cmd == GUICONTROL_CMD_CHOOSE && !IsPureNumeric(aParam3, true, false)) // Must be done only after the above. guicontrol_cmd = GUICONTROL_CMD_CHOOSESTRING; UINT msg, x_msg, y_msg; switch(control.type) { case GUI_CONTROL_DROPDOWNLIST: case GUI_CONTROL_COMBOBOX: msg = (guicontrol_cmd == GUICONTROL_CMD_CHOOSE) ? CB_SETCURSEL : CB_SELECTSTRING; x_msg = CBN_SELCHANGE; y_msg = CBN_SELENDOK; break; case GUI_CONTROL_LISTBOX: if (GetWindowLong(control.hwnd, GWL_STYLE) & (LBS_EXTENDEDSEL|LBS_MULTIPLESEL)) { if (guicontrol_cmd == GUICONTROL_CMD_CHOOSE) msg = LB_SETSEL; else // MSDN: Do not use [LB_SELECTSTRING] with a list box that has the LBS_MULTIPLESEL or the // LBS_EXTENDEDSEL styles: msg = LB_FINDSTRING; } else // single-select listbox if (guicontrol_cmd == GUICONTROL_CMD_CHOOSE) msg = LB_SETCURSEL; else msg = LB_SELECTSTRING; x_msg = LBN_SELCHANGE; y_msg = LBN_DBLCLK; break; default: // Not a supported control type. goto error; } // switch(control.type) if (guicontrol_cmd == GUICONTROL_CMD_CHOOSESTRING) { if (msg == LB_FINDSTRING) { // This msg is needed for multi-select listbox because LB_SELECTSTRING is not supported // in this case. LRESULT found_item = SendMessage(control.hwnd, msg, -1, (LPARAM)aParam3); if (found_item == CB_ERR) // CB_ERR == LB_ERR goto error; if (SendMessage(control.hwnd, LB_SETSEL, TRUE, found_item) == CB_ERR) // CB_ERR == LB_ERR goto error; } else // Fixed 1 to be -1 in v1.0.35.05: if (SendMessage(control.hwnd, msg, -1, (LPARAM)aParam3) == CB_ERR) // CB_ERR == LB_ERR goto error; } else // Choose by position vs. string. { selection_index = ATOI(aParam3) - 1; if (selection_index < -1) goto error; if (msg == LB_SETSEL) // Multi-select, so use the cumulative method. { if (SendMessage(control.hwnd, msg, selection_index >= 0, selection_index) == CB_ERR) // CB_ERR == LB_ERR goto error; } else if (SendMessage(control.hwnd, msg, selection_index, 0) == CB_ERR && selection_index != -1) // CB_ERR == LB_ERR goto error; } int control_id = GUI_INDEX_TO_ID(control_index); if (extra_actions > 0) SendMessage(gui.mHwnd, WM_COMMAND, (WPARAM)MAKELONG(control_id, x_msg), (LPARAM)control.hwnd); if (extra_actions > 1) SendMessage(gui.mHwnd, WM_COMMAND, (WPARAM)MAKELONG(control_id, y_msg), (LPARAM)control.hwnd); goto return_the_result; } // case case GUICONTROL_CMD_FONT: // Done regardless of USES_FONT_AND_TEXT_COLOR to allow future OSes or common control updates // to be given an explicit font, even though it would have no effect currently: SendMessage(control.hwnd, WM_SETFONT, (WPARAM)gui.sFont[gui.mCurrentFontIndex].hfont, 0); if (USES_FONT_AND_TEXT_COLOR(control.type)) // Must check this to avoid corrupting union_hbitmap. { if (control.type != GUI_CONTROL_LISTVIEW) // Must check this to avoid corrupting union col attribs. control.union_color = gui.mCurrentColor; // Used by WM_CTLCOLORSTATIC et. al. for some types of controls. switch (control.type) { case GUI_CONTROL_LISTVIEW: ListView_SetTextColor(control.hwnd, gui.mCurrentColor); // Must use gui.mCurrentColor not control.union_color, see above. break; case GUI_CONTROL_TREEVIEW: TreeView_SetTextColor(control.hwnd, gui.mCurrentColor); break; case GUI_CONTROL_DATETIME: // Since message MCM_SETCOLOR != DTM_SETMCCOLOR, can't combine the two types: DateTime_SetMonthCalColor(control.hwnd, MCSC_TEXT, gui.mCurrentColor); // Hopefully below will revert to default if color is CLR_DEFAULT. break; case GUI_CONTROL_MONTHCAL: MonthCal_SetColor(control.hwnd, MCSC_TEXT, gui.mCurrentColor); // Hopefully below will revert to default if color is CLR_DEFAULT. break; } } InvalidateRect(control.hwnd, NULL, TRUE); // Required for refresh, at least for edit controls, probably some others. // Note: The DateTime_SetMonthCalFont() macro is not used for GUI_CONTROL_DATETIME because // WM_SETFONT+InvalidateRect() above appear to be sufficient for it too. goto return_the_result; } // switch() // If the above didn't return, it wants this check: if ( do_redraw_unconditionally || (tab_control = gui.FindTabControl(control.tab_control_index)) && IsWindowVisible(control.hwnd) ) { GetWindowRect(control.hwnd, &rect); // Limit it to only that part of the client area that is receiving the rect. MapWindowPoints(NULL, gui.mHwnd, (LPPOINT)&rect, 2); // Convert rect to client coordinates (not the same as GetClientRect()). InvalidateRect(gui.mHwnd, &rect, TRUE); // Seems safer to use TRUE, not knowing all possible overlaps, etc. //Overkill: InvalidateRect(gui.mHwnd, NULL, FALSE); // Erase doesn't seem to be necessary. // None of the following is enough: //Changes focused control, so no good: gui.ControlUpdateCurrentTab(*tab_control, false); //RedrawWindow(tab_control->hwnd, NULL, NULL, 0 ..or.. RDW_INVALIDATE); //InvalidateRect(control.hwnd, NULL, TRUE); //InvalidateRect(tab_control->hwnd, NULL, TRUE); } return_the_result: DEPRIVATIZE_S_DEREF_BUF; return result; error: result = SetErrorLevelOrThrow(); goto return_the_result; } ResultType Line::GuiControlGet(LPTSTR aCommand, LPTSTR aControlID, LPTSTR aParam3) { Var &output_var = *OUTPUT_VAR; GuiType *pgui = Script::ResolveGui(aCommand, aCommand); GuiControlGetCmds guicontrolget_cmd = Line::ConvertGuiControlGetCmd(aCommand); if (guicontrolget_cmd == GUICONTROLGET_CMD_INVALID) // This is caught at load-time 99% of the time and can only occur here if the sub-command name // or Gui name is contained in a variable reference. Since it's so rare, the handling of it is // debatable, but to keep it simple just set ErrorLevel: return SetErrorLevelOrThrow(); if (!pgui) // This departs from the tradition used by PerformGui() but since this type of error is rare, // and since use ErrorLevel adds a little bit of flexibility (since the script's current thread // is not unconditionally aborted), this seems best: return SetErrorLevelOrThrow(); GuiType &gui = *pgui; // For performance. if (!*aControlID) // In this case, default to the name of the output variable, as documented. aControlID = output_var.mName; // Beyond this point, errors are rare so set the default to "no error": g_ErrorLevel->Assign(ERRORLEVEL_NONE); PRIVATIZE_S_DEREF_BUF; // GuiControlGet() needs this in case it triggers a callback in the script (e.g. subclassing). See also the comments in GuiControl(). ResultType result = OK; // Set default return value for use with all instances of "goto" further below. // EVERYTHING below this point should use "result" and "goto return_the_result" instead of "return". // Handle GUICONTROLGET_CMD_FOCUS(V) early since it doesn't need a specified ControlID: if (guicontrolget_cmd == GUICONTROLGET_CMD_FOCUS || guicontrolget_cmd == GUICONTROLGET_CMD_FOCUSV) { output_var.Assign(); // Set default to be blank (in case of failure). class_and_hwnd_type cah; cah.hwnd = GetFocus(); GuiControlType *pcontrol; if (!cah.hwnd || !(pcontrol = gui.FindControl(cah.hwnd))) // Relies on short-circuit boolean order. goto error; TCHAR focused_control[WINDOW_CLASS_SIZE]; if (guicontrolget_cmd == GUICONTROLGET_CMD_FOCUSV) // v1.0.43.06. // GUI_HWND_TO_INDEX vs FindControl() is enough because FindControl() was already called above: GuiType::ControlGetName(pgui, GUI_HWND_TO_INDEX(pcontrol->hwnd), focused_control); else // GUICONTROLGET_CMD_FOCUS (ClassNN mode) { // This section is the same as that in ControlGetFocus(): cah.class_name = focused_control; if (!GetClassName(cah.hwnd, focused_control, _countof(focused_control) - 5)) // -5 to allow room for sequence number. goto error; cah.class_count = 0; // Init for the below. cah.is_found = false; // Same. EnumChildWindows(gui.mHwnd, EnumChildFindSeqNum, (LPARAM)&cah); if (!cah.is_found) // Should be impossible due to FindControl() having already found it above. goto error; // Append the class sequence number onto the class name set the output param to be that value: sntprintfcat(focused_control, _countof(focused_control), _T("%d"), cah.class_count); } result = output_var.Assign(focused_control); // And leave ErrorLevel set to NONE. goto return_the_result; } GuiIndexType control_index = gui.FindControl(aControlID); // Fix for v1.1.03: Set output_var only after calling FindControl() so that something like the following will work: ControlGet Control, Hwnd,, %Control% if (guicontrolget_cmd != GUICONTROLGET_CMD_POS) // v1.0.46.09: Avoid resetting the variable for the POS mode, since it uses and array and the user might want the existing contents of the GUI variable retained. output_var.Assign(); // Set default to be blank for all commands except POS, for consistency. if (control_index >= gui.mControlCount) // Not found. goto error; GuiControlType &control = gui.mControl[control_index]; // For performance and convenience. switch(guicontrolget_cmd) { case GUICONTROLGET_CMD_CONTENTS: // Because the below returns FAIL only if a critical error occurred, g_ErrorLevel is // left at NONE as set above for all cases. result = gui.ControlGetContents(output_var, control, aParam3); goto return_the_result; case GUICONTROLGET_CMD_POS: { // In this case, output_var itself is not used directly, but is instead used to: // 1) Help performance by giving us the location in the linked list of variables of // where to find the X/Y/W/H "array elements". // 2) Simplify the code by avoiding the need to classify GuiControlGet's param #1 // as something that is only sometimes a variable. RECT rect; GetWindowRect(control.hwnd, &rect); POINT pt = {rect.left, rect.top}; ScreenToClient(gui.mHwnd, &pt); // Failure seems too rare to check for. // Make it longer than Max var name so that FindOrAddVar() will be able to spot and report // var names that are too long: TCHAR var_name[MAX_VAR_NAME_LENGTH + 20]; Var *var; int always_use = output_var.IsLocal() ? FINDVAR_LOCAL : FINDVAR_GLOBAL; if ( !(var = g_script.FindOrAddVar(var_name , sntprintf(var_name, _countof(var_name), _T("%sX"), output_var.mName) , always_use)) ) { result = FAIL; // It will have already displayed the error. goto return_the_result; } var->Assign(pt.x); if ( !(var = g_script.FindOrAddVar(var_name , sntprintf(var_name, _countof(var_name), _T("%sY"), output_var.mName) , always_use)) ) { result = FAIL; // It will have already displayed the error. goto return_the_result; } var->Assign(pt.y); if ( !(var = g_script.FindOrAddVar(var_name , sntprintf(var_name, _countof(var_name), _T("%sW"), output_var.mName) , always_use)) ) { result = FAIL; // It will have already displayed the error. goto return_the_result; } var->Assign(rect.right - rect.left); if ( !(var = g_script.FindOrAddVar(var_name , sntprintf(var_name, _countof(var_name), _T("%sH"), output_var.mName) , always_use)) ) { result = FAIL; // It will have already displayed the error. goto return_the_result; } result = var->Assign(rect.bottom - rect.top); goto return_the_result; } case GUICONTROLGET_CMD_ENABLED: // See comment below. result = output_var.Assign(IsWindowEnabled(control.hwnd) ? _T("1") : _T("0")); goto return_the_result; case GUICONTROLGET_CMD_VISIBLE: // From working on Window Spy, I seem to remember that IsWindowVisible() uses different standards // for determining visibility than simply checking for WS_VISIBLE is the control and its parent // window. If so, it might be undocumented in MSDN. It is mentioned here to explain why // this "visible" sub-cmd is kept separate from some figure command such as "GuiControlGet, Out, Style": // 1) The style method is cumbersome to script with since it requires bitwise operates afterward. // 2) IsVisible() uses a different standard of detection than simply checking WS_VISIBLE. result = output_var.Assign(IsWindowVisible(control.hwnd) ? _T("1") : _T("0")); goto return_the_result; case GUICONTROLGET_CMD_HWND: // v1.0.46.16: Although it overlaps with HwndOutputVar, Majkinetor wanted this to help with encapsulation/modularization. result = output_var.AssignHWND(control.hwnd); // See also: CONTROLGET_CMD_HWND goto return_the_result; case GUICONTROLGET_CMD_NAME: { // Assign only a variable name rather than falling back to the control's text like ControlGetName, // otherwise the script mightn't be able to distinguish between a control with associated variable // and one which merely contains text similar to a variable name: if (control.output_var) result = output_var.Assign(control.output_var->mName); // Otherwise: leave ErrorLevel 0 and output_var blank, indicating this control exists but has no var. goto return_the_result; } } // switch() result = FAIL; // Should never be reached, but avoids compiler warning and improves bug detection. return_the_result: DEPRIVATIZE_S_DEREF_BUF; return result; error: result = SetErrorLevelOrThrow(); goto return_the_result; } ///////////////// // Static members ///////////////// FontType *GuiType::sFont = NULL; // An array of structs, allocated upon first use. int GuiType::sFontCount = 0; HWND GuiType::sTreeWithEditInProgress = NULL; ResultType GuiType::Destroy(GuiType &gui) // Rather than deal with the confusion of an object destroying itself, this method is static // and designed to deal with one particular window index in the g_gui array. { GuiIndexType u; int i; if (gui.mHwnd) { // First destroy any windows owned by this window, since they will be auto-destroyed // anyway due to their being owned. By destroying them explicitly, the Destroy() // function is called recursively which keeps everything relatively neat. // Search right to left since Destroy() shifts items to the right of i left by 1: for (i = g_guiCount; --i >= 0; ) if (g_gui[i]->mOwner == gui.mHwnd) GuiType::Destroy(*g_gui[i]); // Testing shows that this must be done prior to calling DestroyWindow() later below, presumably // because the destruction immediately destroys the status bar, or prevents it from answering messages. // This seems at odds with MSDN's comment: "During the processing of [WM_DESTROY], it can be assumed // that all child windows still exist". if (gui.mStatusBarHwnd) // IsWindow(gui.mStatusBarHwnd) isn't called because even if possible for it to have been destroyed, SendMessage below should return 0. { // This is done because the vast majority of people wouldn't want to have to worry about it. // They can always use DllCall() if they want to share the same HICON among multiple parts of // the same bar, or among different windows (fairly rare). HICON hicon; int part_count = (int)SendMessage(gui.mStatusBarHwnd, SB_GETPARTS, 0, NULL); // MSDN: "This message always returns the number of parts in the status bar [regardless of how it is called]". for (i = 0; i < part_count; ++i) if (hicon = (HICON)SendMessage(gui.mStatusBarHwnd, SB_GETICON, i, 0)) DestroyIcon(hicon); } if (IsWindow(gui.mHwnd)) // If WM_DESTROY called us, the window might already be partially destroyed. { // If this window is using a menu bar but that menu is also used by some other window, first // detach the menu so that it doesn't get auto-destroyed with the window. This is done // unconditionally since such a menu will be automatically destroyed when the script exits // or when the menu is destroyed explicitly via the Menu command. It also prevents any // submenus attached to the menu bar from being destroyed, since those submenus might be // also used by other menus (however, this is not really an issue since menus destroyed // would be automatically re-created upon next use). But in the case of a window that // is currently using a menu bar, destroying that bar in conjunction with the destruction // of some other window might cause bad side effects on some/all OSes. ShowWindow(gui.mHwnd, SW_HIDE); // Hide it to prevent re-drawing due to menu removal. SetMenu(gui.mHwnd, NULL); if (!gui.mDestroyWindowHasBeenCalled) { gui.mDestroyWindowHasBeenCalled = true; // Signal the WM_DESTROY routine not to call us. DestroyWindow(gui.mHwnd); // The WindowProc is immediately called and it now destroys the window. } // else WM_DESTROY was called by a function other than this one (possibly auto-destruct due to // being owned by script's main window), so it would be bad to call DestroyWindow() again since // it's already in progress. } } // if (gui.mHwnd) // Although it is tempting to do this earlier so that any message monitors or window // procedure subclasses which might have been triggered above could operate on a new // Gui using the same name as this one that's being destroyed, that could break some // scripts since A_Gui and A_GuiControl would not be set correctly: for (i = g_guiCount; --i >= 0; ) // Search right to left (newest first). { if (g_gui[i] == &gui) { // Remove this item by shifting items right of it to the left by 1: while (++i < g_guiCount) g_gui[i-1] = g_gui[i]; --g_guiCount; break; } } if (gui.mBackgroundBrushWin) DeleteObject(gui.mBackgroundBrushWin); if (gui.mBackgroundBrushCtl) DeleteObject(gui.mBackgroundBrushCtl); if (gui.mHdrop) DragFinish(gui.mHdrop); // It seems best to delete the bitmaps whenever the control changes to a new image or // whenever the control is destroyed. Otherwise, if a control or its parent window is // destroyed and recreated many times, memory allocation would continue to grow from // all the abandoned pointers: for (u = 0; u < gui.mControlCount; ++u) { GuiControlType &control = gui.mControl[u]; if (control.type == GUI_CONTROL_PIC && control.union_hbitmap) { if (control.attrib & GUI_CONTROL_ATTRIB_ALTBEHAVIOR) DestroyIcon((HICON)control.union_hbitmap); // Works on cursors too. See notes in LoadPicture(). else // union_hbitmap is a bitmap rather than an icon or cursor. DeleteObject(control.union_hbitmap); //else do nothing, since it isn't the right type to have a valid union_hbitmap member. } else if (control.type == GUI_CONTROL_LISTVIEW) // It was ensured at an earlier stage that union_lv_attrib != NULL. free(control.union_lv_attrib); } HICON icon_eligible_for_destruction = gui.mIconEligibleForDestruction; HICON icon_eligible_for_destruction_small = gui.mIconEligibleForDestructionSmall; if (icon_eligible_for_destruction && icon_eligible_for_destruction != g_script.mCustomIcon) // v1.0.37.07. DestroyIconsIfUnused(icon_eligible_for_destruction, icon_eligible_for_destruction_small); // Must be done only after removal from g_gui. // For simplicity and performance, any fonts used *solely* by a destroyed window are destroyed // only when the program terminates. Another reason for this is that sometimes a destroyed window // is soon recreated to use the same fonts it did before. gui.RemoveAccelerators(); gui.mHwnd = NULL; gui.mControlCount = 0; // All child windows (controls) are automatically destroyed with parent. free(gui.mControl); // Free the control array, which was previously malloc'd. gui.Release(); // After this, the var "gui" is invalid so should not be referenced. return OK; } void GuiType::AddRef() // Keeps the GuiType structure in memory so that Gui destruction can be detected // reliably, but does NOT guarantee that the structure's members will remain valid. { ++mReferenceCount; } void GuiType::Release() { if (--mReferenceCount == 0) { // This should only ever happen if Destroy() has been called and has freed // this structure's contents, although Destroy() mightn't necessarily be // the current/last caller of this function. free(mName); // Free the name, which was previously malloc'd. delete this; } } void GuiType::DestroyIconsIfUnused(HICON ahIcon, HICON ahIconSmall) // Caller has ensured that the GUI window previously using ahIcon has been destroyed prior to calling // this function. { if (!ahIcon) // Caller relies on this check. return; for (int i = 0; i < g_guiCount; ++i) { // If another window is using this icon, don't destroy the because that has been reported to disrupt // the window's display of the icon in some cases (apparently WM_SETICON doesn't make a copy of the // icon). The windows still using the icon will be responsible for destroying it later. if (g_gui[i]->mIconEligibleForDestruction == ahIcon) return; } // Since above didn't return, this icon is not currently in use by a GUI window. The caller has // authorized us to destroy it. DestroyIcon(ahIcon); // L17: Small icon should always also be unused at this point. DestroyIcon(ahIconSmall); } ResultType GuiType::Create() { if (mHwnd) // It already exists return FAIL; // Seems best for now, since it shouldn't really be called this way. // Use a separate class for GUI, which gives it a separate WindowProc and allows it to be more // distinct when used with the ahk_class method of addressing windows. static bool sGuiInitialized = false; if (!sGuiInitialized) { WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_GUI; wc.hInstance = g_hInstance; wc.lpfnWndProc = GuiWindowProc; wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.style = CS_DBLCLKS; // v1.0.44.12: CS_DBLCLKS is accepted as a good default by nearly everyone. It causes the window to receive WM_LBUTTONDBLCLK, WM_RBUTTONDBLCLK, and WM_MBUTTONDBLCLK (even without this, all windows receive WM_NCLBUTTONDBLCLK, WM_NCMBUTTONDBLCLK, and WM_NCRBUTTONDBLCLK). // CS_HREDRAW and CS_VREDRAW are not included above because they cause extra flickering. It's generally better for a window to manage its own redrawing when it's resized. wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wc.cbWndExtra = DLGWINDOWEXTRA; // So that it will be the type that uses DefDlgProc() vs. DefWindowProc(). +#ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class + RegisterClassEx(&wc); +#else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } +#endif sGuiInitialized = true; } if (!mLabelsHaveBeenSet) // i.e. don't set the defaults if the labels were set prior to the creation of the window. SetLabels(NULL); // The above is done prior to creating the window so that mLabelForDropFiles can determine // whether to add the WS_EX_ACCEPTFILES style. if ( !(mHwnd = CreateWindowEx(mExStyle, WINDOW_CLASS_GUI, g_script.mFileName, mStyle, 0, 0, 0, 0 , mOwner, NULL, g_hInstance, NULL)) ) return FAIL; // L17: Use separate big/small icons for best results. HICON big_icon, small_icon; if (g_script.mCustomIcon) { mIconEligibleForDestruction = big_icon = g_script.mCustomIcon; mIconEligibleForDestructionSmall = small_icon = g_script.mCustomIconSmall; // Should always be non-NULL if mCustomIcon is non-NULL. } else big_icon = small_icon = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). // Unlike mCustomIcon, leave mIconEligibleForDestruction NULL because a shared HICON such as one // loaded via LR_SHARED should never be destroyed. // Setting the small icon puts it in the upper left corner of the dialog window. // Setting the big icon makes the dialog show up correctly in the Alt-Tab menu (but big seems to // have no effect unless the window is unowned, i.e. it has a button on the task bar). // Change for v1.0.37.07: Set both icons unconditionally for code simplicity, and also in case // it's possible for the window to change after creation in a way that would make a custom icon // become relevant. Set the big icon even if it's owned because there might be ways // an owned window can have an entry in the alt-tab menu. The following ways come close // but don't actually succeed: // 1) It's owned by the main window but the main window isn't visible: It acquires the main window's icon // in the alt-tab menu regardless of whether it was given a big icon of its own. // 2) It's owned by another GUI window but it has the WS_EX_APPWINDOW style (might force a taskbar button): // Same effect as in #1. // 3) Possibly other ways. SendMessage(mHwnd, WM_SETICON, ICON_SMALL, (LPARAM)small_icon); // Testing shows that a zero is returned for both; SendMessage(mHwnd, WM_SETICON, ICON_BIG, (LPARAM)big_icon); // i.e. there is no previous icon to destroy in this case. return OK; } void GuiType::SetLabels(LPTSTR aLabelPrefix) // v1.0.44.09: Allow custom label prefix to be set; e.g. MyGUI vs. "5Gui" or "2Gui". This increases flexibility // for scripts that dynamically create a varying number of windows, and also allows multiple windows to call the // same set of subroutines. // This function mustn't assume that mHwnd is a valid window because it might not have been created yet. // Caller passes NULL to indicate "use default label prefix" (i.e. the WindowNumber followed by the string "Gui"). // Caller is responsible for checking mLabelsHaveBeenSet as a pre-condition to calling us, if desired. // Caller must ensure that mExStyle is up-to-date if mHwnd is an existing window. In addition, caller must // apply any changes to mExStyle that we make here. { mLabelsHaveBeenSet = true; // Although it's value only matters in some contexts, it's set unconditionally for simplicity. #define MAX_GUI_PREFIX_LENGTH 255 LPTSTR label_suffix; TCHAR label_name[MAX_GUI_PREFIX_LENGTH+64]; // Labels are unlimited in length, but keep prefix+suffix relatively short so that it stays reasonable (to make it easier to limit it in the future should that ever be desirable). if (aLabelPrefix) tcslcpy(label_name, aLabelPrefix, MAX_GUI_PREFIX_LENGTH+1); // Reserve the rest of label_name's size for the suffix below to ensure no chance of overflow. else // Caller is indicating that the defaults should be used. { if (*mName != '1' || mName[1]) // Prepend the window number for windows other than the first. _stprintf(label_name, _T("%sGui"), mName); else _tcscpy(label_name, _T("Gui")); } label_suffix = label_name + _tcslen(label_name); // This is the position at which the rest of the label name will be copied. // Find the label to run automatically when the form closes (if any): _tcscpy(label_suffix, _T("Close")); mLabelForClose = g_script.FindLabel(label_name); // OK if NULL (closing the window is the same as "gui, cancel"). // Find the label to run automatically when the user presses Escape (if any): _tcscpy(label_suffix, _T("Escape")); mLabelForEscape = g_script.FindLabel(label_name); // OK if NULL (pressing ESCAPE does nothing). // Find the label to run automatically when the user resizes the window (if any): _tcscpy(label_suffix, _T("Size")); mLabelForSize = g_script.FindLabel(label_name); // OK if NULL. // Find the label to run automatically when the user invokes context menu via AppsKey, Rightclick, or Shift-F10: _tcscpy(label_suffix, _T("ContextMenu")); mLabelForContextMenu = g_script.FindLabel(label_name); // OK if NULL (leaves context menu unhandled). // Find the label to run automatically when files are dropped onto the window: _tcscpy(label_suffix, _T("DropFiles")); if ((mLabelForDropFiles = g_script.FindLabel(label_name)) // OK if NULL (dropping files is disallowed). && !mHdrop) // i.e. don't allow user to visibly drop files onto window if a drop is already queued or running. mExStyle |= WS_EX_ACCEPTFILES; // Makes the window accept drops. Otherwise, the WM_DROPFILES msg is not received. else mExStyle &= ~WS_EX_ACCEPTFILES; // It is not necessary to apply any style change made above because the caller detects changes and applies them. } void GuiType::UpdateMenuBars(HMENU aMenu) // Caller has changed aMenu and wants the change visibly reflected in any windows that that // use aMenu as a menu bar. For example, if a menu item has been disabled, the grey-color // won't show up immediately unless the window is refreshed. { for (int i = 0; i < g_guiCount; ++i) { //if (g_gui[i]->mHwnd) // Always non-NULL for any item in g_gui. if (GetMenu(g_gui[i]->mHwnd) == aMenu && IsWindowVisible(g_gui[i]->mHwnd)) { // Neither of the below two calls by itself is enough for all types of changes. // Thought it's possible that every type of change only needs one or the other, both // are done for simplicity: // This first line is necessary at least for cases where the height of the menu bar // (the number of rows needed to display all its items) has changed as a result // of the caller's change. In addition, I believe SetWindowPos() must be called // before RedrawWindow() to prevent artifacts in some cases: SetWindowPos(g_gui[i]->mHwnd, NULL, 0, 0, 0, 0, SWP_DRAWFRAME|SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); // This line is necessary at least when a single new menu item has been added: RedrawWindow(g_gui[i]->mHwnd, NULL, NULL, RDW_INVALIDATE|RDW_FRAME|RDW_UPDATENOW); // RDW_UPDATENOW: Seems best so that the window is in an visible updated state when function // returns. This is because if the menu bar happens to be two rows or its size is changed // in any other way, the window dimensions themselves might change, and the caller might // rely on such a change being visibly finished for PixelGetColor, etc. //Not enough: UpdateWindow(g_gui[i]->mHwnd); } } } ResultType GuiType::AddControl(GuiControls aControlType, LPTSTR aOptions, LPTSTR aText) // Caller must have ensured that mHwnd is non-NULL (i.e. that the parent window already exists). { #define TOO_MANY_CONTROLS _T("Too many controls.") // Short msg since so rare. if (mControlCount >= MAX_CONTROLS_PER_GUI) return g_script.ScriptError(TOO_MANY_CONTROLS); if (mControlCount >= mControlCapacity) // The section below on the above check already having been done. { // realloc() to keep the array contiguous, which allows better-performing methods to be // used to access the list of controls in various places. // Expand the array by one block: GuiControlType *realloc_temp; // Needed since realloc returns NULL on failure but leaves original block allocated. if ( !(realloc_temp = (GuiControlType *)realloc(mControl // If passed NULL, realloc() will do a malloc(). , (mControlCapacity + GUI_CONTROL_BLOCK_SIZE) * sizeof(GuiControlType))) ) return g_script.ScriptError(TOO_MANY_CONTROLS); // A non-specific msg since this error is so rare. mControl = realloc_temp; mControlCapacity += GUI_CONTROL_BLOCK_SIZE; } //////////////////////////////////////////////////////////////////////////////////////// // Set defaults for the various options, to be overridden individually by any specified. //////////////////////////////////////////////////////////////////////////////////////// GuiControlType &control = mControl[mControlCount]; ZeroMemory(&control, sizeof(GuiControlType)); if (aControlType == GUI_CONTROL_TAB2) // v1.0.47.05: Replace TAB2 with TAB at an early stage to simplify the code. The only purpose of TAB2 is to flag this as the new type of tab that avoids redrawing issues but has a new z-order that would break some existing scripts. { aControlType = GUI_CONTROL_TAB; control.attrib |= GUI_CONTROL_ATTRIB_ALTBEHAVIOR; // v1.0.47.05: A means for new scripts to solve redrawing problems in tab controls at the cost of putting the tab control after its controls in the z-order. } if (aControlType == GUI_CONTROL_TAB) { if (mTabControlCount == MAX_TAB_CONTROLS) return g_script.ScriptError(_T("Too many tab controls.")); // Short msg since so rare. // For now, don't allow a tab control to be create inside another tab control because it raises // doubt and probably would create complications. If it ever is allowed, note that // control.tab_index stores this tab control's index (0 for the first tab control, 1 for the // second, etc.) -- this is done for performance reasons. control.tab_control_index = MAX_TAB_CONTROLS; control.tab_index = mTabControlCount; // Store its control-index to help look-up performance in other sections. } else if (aControlType == GUI_CONTROL_STATUSBAR) { if (mStatusBarHwnd) return g_script.ScriptError(_T("Too many status bars.")); // Short msg since so rare. control.tab_control_index = MAX_TAB_CONTROLS; // Indicate that bar isn't owned by any tab control. // No need to do the following because ZeroMem did it: //control.tab_index = 0; // Ignored but set for maintainability/consistency. } else { control.tab_control_index = mCurrentTabControlIndex; control.tab_index = mCurrentTabIndex; } // If this is the first control, set the default margin for the window based on the size // of the current font, but only if the margins haven't already been set: if (!mControlCount) { if (mMarginX == COORD_UNSPECIFIED) mMarginX = (int)(1.25 * sFont[mCurrentFontIndex].point_size); // Seems to be a good rule of thumb. if (mMarginY == COORD_UNSPECIFIED) mMarginY = (int)(0.75 * sFont[mCurrentFontIndex].point_size); // Also seems good. mPrevX = mMarginX; // This makes first control be positioned correctly if it lacks both X & Y coords. } control.type = aControlType; // Improves maintainability to do this early, but must be done after TAB2 vs. TAB is resolved higher above. GuiControlOptionsType opt; ControlInitOptions(opt, control); // aOpt.checked is already okay since BST_UNCHECKED == 0 // Similarly, the zero-init of "control" higher above set the right values for password_char, new_section, etc. ///////////////////////////////////////////////// // Set control-specific defaults for any options. ///////////////////////////////////////////////// opt.style_add |= WS_VISIBLE; // Starting default for all control types. opt.use_theme = mUseTheme; // Set default. // Radio buttons are handled separately here, outside the switch() further below: if (aControlType == GUI_CONTROL_RADIO) { // The BS_NOTIFY style is probably better not applied by default to radios because although it // causes the control to send BN_DBLCLK messages, each double-click by the user is seen only // as one click for the purpose of cosmetically making the button appear like it is being // clicked rapidly. Update: the usefulness of double-clicking a radio button seems to // outweigh the rare cosmetic deficiency of rapidly clicking a radio button, so it seems // better to provide it as a default that can be overridden via explicit option. // v1.0.47.04: Removed BS_MULTILINE from default because it is conditionally applied later below. opt.style_add |= BS_NOTIFY; // No WS_TABSTOP here since that is applied elsewhere depending on radio group nature. if (!mInRadioGroup) opt.style_add |= WS_GROUP; // Tabstop must be handled later below. // The mInRadioGroup flag will be changed accordingly after the control is successfully created. //else by default, no WS_TABSTOP or WS_GROUP. However, WS_GROUP can be applied manually via the // options list to split this radio group off from one immediately prior to it. } else // Not a radio. if (mInRadioGroup) // Close out the prior radio group by giving this control the WS_GROUP style. opt.style_add |= WS_GROUP; // This might not be necessary on all OSes, but it seems traditional / best-practice. // Set control's default text color: bool uses_font_and_text_color = USES_FONT_AND_TEXT_COLOR(aControlType); // Resolve macro only once. if (uses_font_and_text_color) // Must check this to avoid corrupting union_hbitmap for PIC controls. { if (control.type != GUI_CONTROL_LISTVIEW) // Must check this to avoid corrupting union_lv_attrib. control.union_color = mCurrentColor; // Default to the most recently set color. opt.color_listview = mCurrentColor; // v1.0.44: Added so that ListViews start off with current font color unless overridden in their options. } else if (aControlType == GUI_CONTROL_PROGRESS) // This must be done to detect custom Progress color. control.union_color = CLR_DEFAULT; // Set progress to default color avoids unnecessary stripping of theme. //else don't change union_color since it shares the same address as union_hbitmap & union_col. switch (aControlType) // Set starting defaults based on control type (the above also does some of that). { // Some controls also have the WS_EX_CLIENTEDGE exstyle by default because they look pretty strange // without them. This seems to be the standard default used by most applications. // Note: It seems that WS_BORDER is hardly ever used in practice with controls, just parent windows. case GUI_CONTROL_DROPDOWNLIST: opt.style_add |= WS_TABSTOP|WS_VSCROLL; // CBS_DROPDOWNLIST is forcibly applied later. WS_VSCROLL is necessary. break; case GUI_CONTROL_COMBOBOX: // CBS_DROPDOWN is set as the default here to allow the flexibility for it to be changed to // CBS_SIMPLE. CBS_SIMPLE is allowed for ComboBox but not DropDownList because CBS_SIMPLE // has an edit control just like a combo, which DropDownList isn't equipped to handle via Submit(). // Also, if CBS_AUTOHSCROLL is omitted, typed text cannot go beyond the visible width of the // edit control, so it seems best to have that as a default also: opt.style_add |= WS_TABSTOP|WS_VSCROLL|CBS_AUTOHSCROLL|CBS_DROPDOWN; // WS_VSCROLL is necessary. break; case GUI_CONTROL_LISTBOX: // Omit LBS_STANDARD because it includes LBS_SORT, which we don't want as a default style. // However, as of v1.0.30.03, LBS_USETABSTOPS is included by default because: // 1) Not doing so seems to make it impossible to apply tab stops after the control has been created. // 2) Without this style, tabs appears as empty squares in the text, which seems undesirable for // 99.9% of applications. // 3) LBS_USETABSTOPS can be explicitly removed by specifying -0x80 in the options of "Gui Add". opt.style_add |= WS_TABSTOP|WS_VSCROLL|LBS_USETABSTOPS; // WS_VSCROLL seems the most desirable default. opt.exstyle_add |= WS_EX_CLIENTEDGE; break; case GUI_CONTROL_LISTVIEW: // The ListView extended styles are actually an entirely separate class of styles that exist // separately from ExStyles. This explains why Get/SetWindowLong doesn't work on them. // But keep in mind that some of the normal/classic extended styles can still be applied // to a ListView via Get/SetWindowLong. // The listview extended styles all require at least ComCtl32.dll 4.70 (some might require more) // and thus will have no effect in Win 95/NT unless they have MSIE 3.x or similar patch installed. // Thus, things like LVS_EX_FULLROWSELECT and LVS_EX_HEADERDRAGDROP will have no effect on those systems. opt.listview_style |= LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP; // LVS_AUTOARRANGE seems to disrupt the display of the column separators and have other weird effects in Report view. opt.style_add |= WS_TABSTOP|LVS_SHOWSELALWAYS; // LVS_REPORT is omitted to help catch bugs involving opt.listview_view. WS_THICKFRAME allows the control itself to be drag-resized. opt.exstyle_add |= WS_EX_CLIENTEDGE; // WS_EX_STATICEDGE/WS_EX_WINDOWEDGE/WS_BORDER(non-ex) don't look as nice. WS_EX_DLGMODALFRAME is a weird but interesting effect. opt.listview_view = LVS_REPORT; // Improves maintainability by avoiding the need to check if it's -1 in other places. break; case GUI_CONTROL_TREEVIEW: // Default style is somewhat debatable, but the familiarity of Explorer's own defaults seems best. // TVS_SHOWSELALWAYS seems preferable by most people, and is also consistent to what is used for ListView. // Lines and buttons also seem preferable because the main feature of a tree is its hierarchical nature, // and that nature isn't well revealed without buttons, and buttons can't be shown at the root level // without TVS_LINESATROOT, which in turn can't be active without TVS_HASLINES. opt.style_add |= WS_TABSTOP|TVS_SHOWSELALWAYS|TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS; // TVS_LINESATROOT is necessary to get plus/minus buttons on root-level items. opt.exstyle_add |= WS_EX_CLIENTEDGE; // Debatable, but seems best for consistency with ListView. break; case GUI_CONTROL_EDIT: opt.style_add |= WS_TABSTOP; opt.exstyle_add |= WS_EX_CLIENTEDGE; break; case GUI_CONTROL_LINK: opt.style_add |= WS_TABSTOP; break; case GUI_CONTROL_UPDOWN: // UDS_NOTHOUSANDS is debatable: // 1) The primary means by which a script validates whether the buddy contains an invalid // or out-of-range value for its UpDown is to compare the contents of the two. If one // has commas and the other doesn't, the commas must first be removed before comparing. // 2) Presence of commas in numeric data is going to be a source of script bugs for those // who take the buddy's contents rather than the UpDown's contents as the user input. // However, you could argue that script is not proper if it does this blindly because // the buddy could contain an out-of-range or non-numeric value. // 3) Display is more ergonomic if it has commas in it. // The above make it pretty hard to decide, so sticking with the default of have commas // seems ok. Also, UDS_ALIGNRIGHT must be present by default because otherwise buddying // will not take effect correctly. opt.style_add |= UDS_SETBUDDYINT|UDS_ALIGNRIGHT|UDS_AUTOBUDDY|UDS_ARROWKEYS; break; case GUI_CONTROL_DATETIME: // Gets a tabstop even when it contains an empty checkbox indicating "no date". // DTS_SHORTDATECENTURYFORMAT is applied by default because it should make results more consistent // across old and new systems. This is because new systems display a 4-digit year even without // this style, but older ones might display a two digit year. This should make any system capable // of displaying a 4-digit year display it in the locale's customary format. On systems that don't // support DTS_SHORTDATECENTURYFORMAT, it should be ignored, resulting in DTS_SHORTDATEFORMAT taking // effect automatically (untested). opt.style_add |= WS_TABSTOP|DTS_SHORTDATECENTURYFORMAT; break; case GUI_CONTROL_BUTTON: // v1.0.45: Removed BS_MULTILINE from default because it is conditionally applied later below. case GUI_CONTROL_CHECKBOX: // v1.0.47.04: Removed BS_MULTILINE from default because it is conditionally applied later below. case GUI_CONTROL_HOTKEY: case GUI_CONTROL_SLIDER: opt.style_add |= WS_TABSTOP; break; case GUI_CONTROL_PROGRESS: opt.style_add |= PBS_SMOOTH; // The smooth ones seem preferable as a default. Theme is removed later below. break; case GUI_CONTROL_TAB: // Override the normal default, requiring a manual +Theme in the control's options. This is done // because themed tabs have a gradient background that is currently not well supported by the method // used here (controls' backgrounds do not match the gradient): opt.use_theme = false; opt.style_add |= WS_TABSTOP|TCS_MULTILINE; break; case GUI_CONTROL_ACTIVEX: opt.style_add |= WS_CLIPSIBLINGS; break; case GUI_CONTROL_STATUSBAR: // Although the following appears unnecessary, at least on XP, there's a good chance it's required // on older OSes such as Win 95/NT. On newer OSes, apparently the control shows a grip on // its own even though it doesn't even give itself the SBARS_SIZEGRIP style. if (mStyle & WS_SIZEBOX) // Parent window is resizable. opt.style_add |= SBARS_SIZEGRIP; // Provide a grip by default. // Below: Seems best to provide SBARS_TOOLTIPS by default, since we're not bound by backward compatibility // like the OS is. In theory, tips should be displayed only when the script has actually set some tip text // (e.g. via SendMessage). In practice, tips are never displayed, even under the precise conditions // described at MSDN's SB_SETTIPTEXT, perhaps under certain OS versions and themes. See bottom of // BIF_StatusBar() for more comments. opt.style_add |= SBARS_TOOLTIPS; break; // Nothing extra for these currently: //case GUI_CONTROL_RADIO: This one is handled separately above the switch(). //case GUI_CONTROL_TEXT: //case GUI_CONTROL_MONTHCAL: Can't be focused, so no tabstop. //case GUI_CONTROL_PIC: //case GUI_CONTROL_GROUPBOX: // v1.0.44.11: The following was commented out for GROUPBOX to avoid unwanted wrapping of last letter when // the font is bold on XP Classic theme (other font styles and desktop themes may also be cause this). // Avoiding this problem seems to outweigh the breaking of old scripts that use GroupBoxes with more than // one line of text (which are likely to be very rare). //opt.style_add |= BS_MULTILINE; break; } ///////////////////////////// // Parse the list of options. ///////////////////////////// if (!ControlParseOptions(aOptions, opt, control)) return FAIL; // It already displayed the error. // The following is needed by ControlSetListViewOptions/ControlSetTreeViewOptions, and possibly others // in the future. It must be done only after ControlParseOptions() so that cases where mCurrentColor // is not CLR_DEFAULT but the options contained cDefault are handled properly. // The following will set opt.color_changed to an invalid value for GUI_CONTROL_PIC (which stores something // else in the union_color's union) and other types that don't even use union_color for anything yet. But // that should be okay because those types should never consult opt.color_changed. opt.color_changed = CLR_DEFAULT != (aControlType == GUI_CONTROL_LISTVIEW ? opt.color_listview : control.union_color); if (opt.color_bk == CLR_DEFAULT) // i.e. the options list must have explicitly specified BackgroundDefault. opt.color_bk = CLR_INVALID; // Tell things like ControlSetListViewOptions "no color change needed". else if (opt.color_bk == CLR_INVALID && mBackgroundColorCtl != CLR_DEFAULT // No bk color was specified in options param. && aControlType != GUI_CONTROL_PROGRESS && aControlType != GUI_CONTROL_STATUSBAR) // And the control obeys the current "Gui, Color,, CtlBkColor". Status bars don't obey it because it seems slightly less desirable for most people, and also because system default bar color might be diff. than system default win color on some themes. // Since bkgnd color was not explicitly specified in options, use the current background color (except progress bars, which do their own thing). opt.color_bk = mBackgroundColorCtl; // Use window's global custom, control background. //else leave it as invalid so that ControlSetListView/TreeView/ProgressOptions() etc. won't bother changing it. // Change for v1.0.45 (buttons) and v1.0.47.04 (checkboxes and radios): Under some desktop themes and // unusual DPI settings, it has been reported that the last letter of the control's text gets truncated // and/or causes an unwanted wrap that prevents proper display of the text. To solve this, default to // "wrapping enabled" only when necessary. One case it's usually necessary is when there's an explicit // width present because then the text can automatically word-wrap to the next line if it contains any // spaces/tabs/dashes (this also improves backward compatibility). DWORD contains_bs_multiline_if_applicable = (opt.width != COORD_UNSPECIFIED || opt.height != COORD_UNSPECIFIED || opt.row_count > 1.5 || StrChrAny(aText, _T("\n\r"))) // Both LF and CR can start new lines. ? (BS_MULTILINE & ~opt.style_remove) // Add BS_MULTILINE unless it was explicitly removed. : 0; // Otherwise: Omit BS_MULTILINE (unless it was explicitly added [the "0" is verified correct]) because on some unusual DPI settings (i.e. DPIs other than 96 or 120), DrawText() sometimes yields a width that is slightly too narrow, which causes unwanted wrapping in single-line checkboxes/radios/buttons. DWORD style = opt.style_add & ~opt.style_remove; DWORD exstyle = opt.exstyle_add & ~opt.exstyle_remove; ////////////////////////////////////////// // Force any mandatory styles into effect. ////////////////////////////////////////// style |= WS_CHILD; // All control types must have this, even if script attempted to remove it explicitly. switch (aControlType) { case GUI_CONTROL_GROUPBOX: // There doesn't seem to be any flexibility lost by forcing the buttons to be the right type, // and doing so improves maintainability and peace-of-mind: style = (style & ~BS_TYPEMASK) | BS_GROUPBOX; // Force it to be the right type of button. break; case GUI_CONTROL_BUTTON: if (style & BS_DEFPUSHBUTTON) // i.e. its single bit is present. BS_TYPEMASK is not involved in this line because it's a purity check. style = (style & ~BS_TYPEMASK) | BS_DEFPUSHBUTTON; // Done to ensure the lowest four bits are pure. else style &= ~BS_TYPEMASK; // Force it to be the right type of button --> BS_PUSHBUTTON == 0 style |= contains_bs_multiline_if_applicable; break; case GUI_CONTROL_CHECKBOX: // Note: BS_AUTO3STATE and BS_AUTOCHECKBOX are mutually exclusive due to their overlap within // the bit field: if ((style & BS_AUTO3STATE) == BS_AUTO3STATE) // Fixed for v1.0.45.03 to check if all the BS_AUTO3STATE bits are present, not just "any" of them. BS_TYPEMASK is not involved here because this is a purity check, and TYPEMASK would defeat the whole purpose. style = (style & ~BS_TYPEMASK) | BS_AUTO3STATE; // Done to ensure the lowest four bits are pure. else style = (style & ~BS_TYPEMASK) | BS_AUTOCHECKBOX; // Force it to be the right type of button. style |= contains_bs_multiline_if_applicable; // v1.0.47.04: Added to avoid unwanted wrapping on systems with unusual DPI settings (DPIs other than 96 and 120 sometimes seem to cause a roundoff problem with DrawText()). break; case GUI_CONTROL_RADIO: style = (style & ~BS_TYPEMASK) | BS_AUTORADIOBUTTON; // Force it to be the right type of button. // This below must be handled here rather than in the set-defaults section because this // radio might be the first of its group due to the script having explicitly specified the word // Group in options (useful to make two adjacent radio groups). if (style & WS_GROUP && !(opt.style_remove & WS_TABSTOP)) style |= WS_TABSTOP; // Otherwise it lacks a tabstop by default. style |= contains_bs_multiline_if_applicable; // v1.0.47.04: Added to avoid unwanted wrapping on systems with unusual DPI settings (DPIs other than 96 and 120 sometimes seem to cause a roundoff problem with DrawText()). break; case GUI_CONTROL_DROPDOWNLIST: style |= CBS_DROPDOWNLIST; // This works because CBS_DROPDOWNLIST == CBS_SIMPLE|CBS_DROPDOWN break; case GUI_CONTROL_COMBOBOX: if (style & CBS_SIMPLE) // i.e. CBS_SIMPLE has been added to the original default, so assume it is SIMPLE. style = (style & ~0x0F) | CBS_SIMPLE; // Done to ensure the lowest four bits are pure. else style = (style & ~0x0F) | CBS_DROPDOWN; // Done to ensure the lowest four bits are pure. break; case GUI_CONTROL_LISTBOX: style |= LBS_NOTIFY; // There doesn't seem to be any flexibility lost by forcing this style. break; case GUI_CONTROL_EDIT: // This is done for maintainability and peace-of-mind, though it might not strictly be required // to be done at this stage: if (opt.row_count > 1.5 || _tcschr(aText, '\n')) // Multiple rows or contents contain newline. style |= (ES_MULTILINE & ~opt.style_remove); // Add multiline unless it was explicitly removed. // This next check is relied upon by other things. If this edit has the multiline style either // due to the above check or any other reason, provide other default styles if those styles // weren't explicitly removed in the options list: if (style & ES_MULTILINE) // If allowed, enable vertical scrollbar and capturing of ENTER keystrokes. // Safest to include ES_AUTOVSCROLL, though it appears to have no effect on XP. See also notes below: #define EDIT_MULTILINE_DEFAULT (WS_VSCROLL|ES_WANTRETURN|ES_AUTOVSCROLL) style |= EDIT_MULTILINE_DEFAULT & ~opt.style_remove; // In addition, word-wrapping is implied unless explicitly disabled via -wrap in options. // This is because -wrap adds the ES_AUTOHSCROLL style. // else: Single-line edit. ES_AUTOHSCROLL will be applied later below if all the other checks // fail to auto-detect this edit as a multi-line edit. // Notes: ES_MULTILINE is required for any CRLFs in the default value to display correctly. // If ES_MULTILINE is in effect: "If you do not specify ES_AUTOHSCROLL, the control automatically // wraps words to the beginning of the next line when necessary." // Also, ES_AUTOVSCROLL seems to have no additional effect, perhaps because this window type // is considered to be a dialog. MSDN: "When the multiline edit control is not in a dialog box // and the ES_AUTOVSCROLL style is specified, the edit control shows as many lines as possible // and scrolls vertically when the user presses the ENTER key. If you do not specify ES_AUTOVSCROLL, // the edit control shows as many lines as possible and beeps if the user presses the ENTER key when // no more lines can be displayed." break; case GUI_CONTROL_TAB: style |= WS_CLIPSIBLINGS; // MSDN: Both the parent window and the tab control must have the WS_CLIPSIBLINGS window style. // TCS_OWNERDRAWFIXED is required to implement custom Text color in the tabs. // For some reason, it's also required for TabWindowProc's WM_ERASEBKGND to be able to // override the background color of the control's interior, at least when an XP theme is in effect. // (which is currently impossible since theme is always removed from a tab). // Even if that weren't the case, would still want owner-draw because otherwise the background // color of the tab-text would be different than the tab's interior, which testing shows looks // pretty strange. if (mBackgroundBrushWin && !(control.attrib & GUI_CONTROL_ATTRIB_BACKGROUND_DEFAULT) || control.union_color != CLR_DEFAULT) style |= TCS_OWNERDRAWFIXED; else style &= ~TCS_OWNERDRAWFIXED; break; // Nothing extra for these currently: //case GUI_CONTROL_TEXT: Ensuring SS_BITMAP and such are absent seems too over-protective. //case GUI_CONTROL_LINK: //case GUI_CONTROL_PIC: SS_BITMAP/SS_ICON are applied after the control isn't created so that it doesn't try to auto-load a resource. //case GUI_CONTROL_LISTVIEW: //case GUI_CONTROL_TREEVIEW: //case GUI_CONTROL_DATETIME: //case GUI_CONTROL_MONTHCAL: //case GUI_CONTROL_HOTKEY: //case GUI_CONTROL_UPDOWN: //case GUI_CONTROL_SLIDER: //case GUI_CONTROL_PROGRESS: //case GUI_CONTROL_ACTIVEX: //case GUI_CONTROL_STATUSBAR: } //////////////////////////////////////////////////////////////////////////////////////////// // If the above didn't already set a label for this control and this control type qualifies, // check if an automatic/implicit label exists for it in the script. ////////////////////////////////////////////////////////////////////////////////////////////
tinku99/ahkdll
6edfb2fe3087271fc0a0edd7d365866f57a65590
Fix ahkFunction and other to support calling build in functions
diff --git a/source/exports.cpp b/source/exports.cpp index ce25c06..3ad7d3a 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,745 +1,707 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. +VARIANT variant_to_return_dll; // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; +void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(int timeout){return ahkTerminate(timeout);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { - // g_script.mTempFunc = aFunc ; - // ExprTokenType return_value; - if (aFunc->mParamCount > 0 && param1 != NULL) + int aParamCount = 0; + LPTSTR *params[10]; + params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; + params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; + if(aFunc->mIsBuiltIn) { - // Copy the appropriate values into each of the function's formal parameters. - aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 - if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 + ResultType aResult = OK; + ExprTokenType aResultToken; + ExprTokenType **aParam = (ExprTokenType**)alloca(sizeof(ExprTokenType)*10); + for (;aFunc->mParamCount > aParamCount && params[aParamCount] != NULL && *params[aParamCount];aParamCount++) { - // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages - // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because - // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for - // commands such as PostMessage/SendMessage. - aFunc->mParam[1].var->Assign((LPTSTR )param2); - if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 - { - aFunc->mParam[2].var->Assign((LPTSTR )param3); - if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 - { - aFunc->mParam[3].var->Assign((LPTSTR )param4); - if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 - { - aFunc->mParam[4].var->Assign((LPTSTR )param5); - if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 - { - aFunc->mParam[5].var->Assign((LPTSTR )param6); - if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 - { - aFunc->mParam[6].var->Assign((LPTSTR )param7); - if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 - { - aFunc->mParam[7].var->Assign((LPTSTR )param8); - if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 - { - aFunc->mParam[8].var->Assign((LPTSTR )param9); - if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 - { - aFunc->mParam[9].var->Assign((LPTSTR )param10); - } - } - } - } - } - } - } - } + aParam[aParamCount] = (ExprTokenType*)alloca(sizeof(ExprTokenType)); + aParam[aParamCount]->symbol = SYM_STRING;aParam[aParamCount]->marker = *params[aParamCount];aParamCount++; // Assign parameter #1 } + aResultToken.symbol = PURE_INTEGER; + aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); + return 0; } - - FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; - aFuncAndToken.mFunc = aFunc ; - returnCount++ ; - if (returnCount > 9) - returnCount = 0 ; - PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); - return 0; - } - return -1; + else + { + for (;aFunc->mParamCount > aParamCount && params[aParamCount] != NULL && *params[aParamCount];aParamCount++) + aFunc->mParam[aParamCount].var->Assign(*params[aParamCount]); + FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; + aFuncAndToken.mFunc = aFunc ; + returnCount++ ; + if (returnCount > 9) + returnCount = 0 ; + PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); + return 0; + } + } + else // Function not found + return -1; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { - // g_script.mTempFunc = aFunc ; - // ExprTokenType return_value; - if (aFunc->mParamCount > 0 && param1 != NULL) + int aParamCount = 0; + LPTSTR *params[10]; + params[0]=&param1;params[1]=&param2;params[2]=&param3;params[3]=&param4;params[4]=&param5; + params[5]=&param6;params[6]=&param7;params[7]=&param8;params[8]=&param9;params[9]=&param10; + if(aFunc->mIsBuiltIn) { - // Copy the appropriate values into each of the function's formal parameters. - aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 - if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 + ResultType aResult = OK; + ExprTokenType aResultToken; + ExprTokenType **aParam = (ExprTokenType**)alloca(sizeof(ExprTokenType)*10); + for (;aFunc->mParamCount > aParamCount && params[aParamCount] != NULL && *params[aParamCount];aParamCount++) + { + aParam[aParamCount] = (ExprTokenType*)alloca(sizeof(ExprTokenType)); + aParam[aParamCount]->symbol = SYM_STRING;aParam[aParamCount]->marker = *params[aParamCount];aParamCount++; // Assign parameter #1 + } + aResultToken.symbol = PURE_INTEGER; + aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); + switch (aResultToken.symbol) { - // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages - // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because - // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for - // commands such as PostMessage/SendMessage. - aFunc->mParam[1].var->Assign((LPTSTR )param2); - if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 + case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. + if (_tcslen(aResultToken.var->Contents())) { - aFunc->mParam[2].var->Assign((LPTSTR )param3); - if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 - { - aFunc->mParam[3].var->Assign((LPTSTR )param4); - if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 - { - aFunc->mParam[4].var->Assign((LPTSTR )param5); - if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 - { - aFunc->mParam[5].var->Assign((LPTSTR )param6); - if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 - { - aFunc->mParam[6].var->Assign((LPTSTR )param7); - if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 - { - aFunc->mParam[7].var->Assign((LPTSTR )param8); - if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 - { - aFunc->mParam[8].var->Assign((LPTSTR )param9); - if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 - { - aFunc->mParam[9].var->Assign((LPTSTR )param10); - } - } - } - } - } - } - } + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.var->Contents())*sizeof(TCHAR)); + _tcscpy(result_to_return_dll,aResultToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } + else if (result_to_return_dll) + *result_to_return_dll = '\0'; + break; + case SYM_STRING: + case SYM_OPERAND: + if (_tcslen(aResultToken.marker)) + { + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,_tcslen(aResultToken.marker)*sizeof(TCHAR)); + _tcscpy(result_to_return_dll,aResultToken.marker); + } + else if (result_to_return_dll) + *result_to_return_dll = '\0'; + break; + case SYM_INTEGER: + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); + ITOA64(aResultToken.value_int64, result_to_return_dll); + break; + case SYM_FLOAT: + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); + sntprintf(result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aResultToken.value_double); + break; + //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). + default: // Not an operand: continue on to return the default at the bottom. + result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); + ITOA64(aResultToken.value_int64, result_to_return_dll); } + return result_to_return_dll; + } + else // UDF + { + for (;aFunc->mParamCount > aParamCount && params[aParamCount] != NULL && *params[aParamCount];aParamCount++) + aFunc->mParam[aParamCount].var->Assign(*params[aParamCount]); + FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; + aFuncAndToken.mFunc = aFunc ; + returnCount++ ; + if (returnCount > 9) + returnCount = 0 ; + SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); + return aFuncAndToken.result_to_return_dll; } - - FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; - aFuncAndToken.mFunc = aFunc ; - returnCount++ ; - if (returnCount > 9) - returnCount = 0 ; - - SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); - return aFuncAndToken.result_to_return_dll; } - else + else // Function not found return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { - // g_script.mTempFunc = aFunc ; - // ExprTokenType return_value; - if (aFunc->mParamCount > 0 && &param1 != NULL) + VARIANT *variants[10]; + int aParamCount = 0; + variants[0]=&param1;variants[1]=&param2;variants[2]=&param3;variants[3]=&param4;variants[4]=&param5; + variants[5]=&param6;variants[6]=&param7;variants[7]=&param8;variants[8]=&param9;variants[9]=&param10; + if(aFunc->mIsBuiltIn) { - // Copy the appropriate values into each of the function's formal parameters. - AssignVariant(*aFunc->mParam[0].var, param1); // Assign parameter #1 - if (aFunc->mParamCount > 1 && param2.vt != VT_ERROR) // Assign parameter #2 + ResultType aResult = OK; + ExprTokenType aResultToken; + ExprTokenType **aParam = (ExprTokenType**)alloca(sizeof(ExprTokenType)*10); + void *var_type = (void *)VAR_NORMAL; + for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) { - // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages - // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because - // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for - // commands such as PostMessage/SendMessage. - AssignVariant(*aFunc->mParam[1].var, param2); - if (aFunc->mParamCount > 2 && param3.vt != VT_ERROR) // Assign parameter #3 - { - AssignVariant(*aFunc->mParam[2].var, param3); - if (aFunc->mParamCount > 3 && param4.vt != VT_ERROR) // Assign parameter #4 - { - AssignVariant(*aFunc->mParam[3].var, param4); - if (aFunc->mParamCount > 4 && param5.vt != VT_ERROR) // Assign parameter #5 - { - AssignVariant(*aFunc->mParam[4].var, param5); - if (aFunc->mParamCount > 5 && param6.vt != VT_ERROR) // Assign parameter #6 - { - AssignVariant(*aFunc->mParam[5].var, param6); - if (aFunc->mParamCount > 6 && param7.vt != VT_ERROR) // Assign parameter #7 - { - AssignVariant(*aFunc->mParam[6].var, param7); - if (aFunc->mParamCount > 7 && param8.vt != VT_ERROR) // Assign parameter #8 - { - AssignVariant(*aFunc->mParam[7].var, param8); - if (aFunc->mParamCount > 8 && param9.vt != VT_ERROR) // Assign parameter #9 - { - AssignVariant(*aFunc->mParam[8].var, param9); - if (aFunc->mParamCount > 9 && param10.vt != VT_ERROR) // Assign parameter #10 - { - AssignVariant(*aFunc->mParam[9].var, param10); - } - } - } - } - } - } - } - } + aParam[aParamCount] = (ExprTokenType*)alloca(sizeof(ExprTokenType)); + aParam[aParamCount]->symbol = SYM_VAR; + aParam[aParamCount]->var = new Var(_T(""),var_type,VAR_NORMAL); + AssignVariant(*aParam[aParamCount]->var, *variants[aParamCount]); } + aResultToken.symbol = PURE_INTEGER; + aFunc->mBIF(aResult,aResultToken,aParam,aParamCount); + TokenToVariant(aResultToken, variant_to_return_dll); + return variant_to_return_dll; } - - FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; - aFuncAndToken.mFunc = aFunc ; - returnCount++ ; - if (returnCount > 9) - returnCount = 0 ; - - if (sendOrPost == 1) - { - SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); - return aFuncAndToken.variant_to_return_dll; - } - else + else // UDF { - PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); - VARIANT &r = aFuncAndToken.variant_to_return_dll; - r.vt = VT_NULL ; - return r ; - } + for (;aFunc->mParamCount > aParamCount && variants[aParamCount]->vt != VT_ERROR;aParamCount++) + AssignVariant(*aFunc->mParam[aParamCount].var, *variants[aParamCount]); + FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; + aFuncAndToken.mFunc = aFunc ; + returnCount++ ; + if (returnCount > 9) + returnCount = 0 ; + + if (sendOrPost == 1) + { + SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); + return aFuncAndToken.variant_to_return_dll; + } + else + { + PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); + VARIANT &r = aFuncAndToken.variant_to_return_dll; + r.vt = VT_NULL ; + return r ; + } } + } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } - -void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); - void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/resources/AutoHotkey.rc.orig b/source/resources/AutoHotkey.rc.orig deleted file mode 100644 index 1e5e292..0000000 --- a/source/resources/AutoHotkey.rc.orig +++ /dev/null @@ -1,239 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -//#include "afxres.h" -#include <winresrc.h> - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// RT_MANIFEST -// - -#ifdef EMBED_MANIFEST // VC++ 2005 and later don't require the next line. -CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "AutoHotkey.exe.manifest" -#endif - -// TYPELIB -// ReleaseDll must be build before DebugDll to update .tlb file -#ifdef _USRDLL -#ifdef _WIN64 -1 TYPELIB "temp\\x64\\ReleaseDll\\AutoHotkey.tlb" -#else -#ifdef _UNICODE -1 TYPELIB "temp\\Win32\\ReleaseDll\\AutoHotkey.tlb" -#else -1 TYPELIB "temp\\Win32\\ReleaseDll(mbcs)\\AutoHotkey.tlb" -#endif -#endif -#endif - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "//#include ""afxres.h""\r\n" - "#include <winresrc.h>\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#ifndef MINIDLL -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU_MAIN MENU -BEGIN - POPUP "&File" - BEGIN - MENUITEM "&Reload Script\tCtrl+R", ID_FILE_RELOADSCRIPT - MENUITEM "&Edit Script\tCtrl+E", ID_FILE_EDITSCRIPT - MENUITEM "&Window Spy", ID_FILE_WINDOWSPY - MENUITEM SEPARATOR - MENUITEM "&Pause Script\tPause", ID_FILE_PAUSE - MENUITEM "&Suspend Hotkeys", ID_FILE_SUSPEND - MENUITEM SEPARATOR - MENUITEM "E&xit (Terminate Script)", ID_FILE_EXIT - END - POPUP "&View" - BEGIN - MENUITEM "&Lines most recently executed\tCtrl+L", ID_VIEW_LINES - MENUITEM "&Variables and their contents\tCtrl+V", ID_VIEW_VARIABLES - MENUITEM "&Hotkeys and their methods\tCtrl+H", ID_VIEW_HOTKEYS - MENUITEM "&Key history and script info\tCtrl+K", ID_VIEW_KEYHISTORY - MENUITEM SEPARATOR - MENUITEM "&Refresh\tF5", ID_VIEW_REFRESH - END - POPUP "&Help" - BEGIN - MENUITEM "&User Manual\tF1", ID_HELP_USERMANUAL - MENUITEM "&Web Site", ID_HELP_WEBSITE - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_MAIN ICON "icon_main.ico" -IDI_SUSPEND ICON "icon_suspend.ico" -IDI_PAUSE ICON "icon_pause.ico" -IDI_PAUSE_SUSPEND ICON "icon_pause_suspend.ico" -IDI_FILETYPE ICON "icon_filetype.ico" -IDI_TRAY_WIN9X ICON "icon_tray_win9x.ico" -IDI_TRAY_WIN9X_SUSPEND ICON "icon_tray_win9x_suspend.ico" -IDI_TRAY ICON "icon_tray.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_INPUTBOX DIALOGEX 0, 0, 210, 83 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | - WS_CAPTION | WS_SYSMENU | WS_THICKFRAME -CAPTION "Dialog" -FONT 10, "MS Shell Dlg", 400, 0, 0x0 -BEGIN - EDITTEXT IDC_INPUTEDIT,2,51,207,12,ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,51,67,31,12 - PUSHBUTTON "Cancel",IDCANCEL,129,67,31,12 - LTEXT "Prompt",IDC_INPUTPROMPT,3,2,205,48 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDR_ACCELERATOR1 ACCELERATORS -BEGIN - VK_F1, ID_HELP_USERMANUAL, VIRTKEY, NOINVERT - "H", ID_VIEW_HOTKEYS, VIRTKEY, CONTROL, NOINVERT - "K", ID_VIEW_KEYHISTORY, VIRTKEY, CONTROL, NOINVERT - "L", ID_VIEW_LINES, VIRTKEY, CONTROL, NOINVERT - VK_F5, ID_VIEW_REFRESH, VIRTKEY, NOINVERT - "V", ID_VIEW_VARIABLES, VIRTKEY, CONTROL, NOINVERT - VK_PAUSE, ID_FILE_PAUSE, VIRTKEY, NOINVERT - "E", ID_FILE_EDITSCRIPT, VIRTKEY, CONTROL, NOINVERT - "R", ID_FILE_RELOADSCRIPT, VIRTKEY, CONTROL, NOINVERT -END -#endif - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#include "..\ahkversion.h" - -VS_VERSION_INFO VERSIONINFO - FILEVERSION AHK_VERSION_N - PRODUCTVERSION AHK_VERSION_N - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN -#ifdef AUTOHOTKEYSC - VALUE "FileDescription", "" - VALUE "FileVersion", AHK_VERSION - VALUE "InternalName", "" - VALUE "LegalCopyright", "" - VALUE "OriginalFilename", "" - VALUE "ProductName", "" - VALUE "ProductVersion", AHK_VERSION -#else - VALUE "FileDescription", "AutoHotkey_H" - VALUE "FileVersion", AHK_VERSION - VALUE "InternalName", "AutoHotkey_H" - VALUE "LegalCopyright", "Copyright (C) 2010" -#ifdef USRDLL - #ifdef MINIDLL - VALUE "OriginalFilename", "AutoHotkeyMini.dll" - #else - VALUE "OriginalFilename", "AutoHotkey.dll" - #endif -#else - VALUE "OriginalFilename", "AutoHotkey.exe" -#endif - VALUE "ProductName", "AutoHotkey_H" - VALUE "ProductVersion", AHK_VERSION -#endif - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - - -#ifdef _DEBUG -AHK RCDATA "d:\\Temp\\AHF\\test.ahk" -#endif \ No newline at end of file diff --git a/source/utils.h b/source/utils.h deleted file mode 100644 index 7eb9a7a..0000000 --- a/source/utils.h +++ /dev/null @@ -1,7 +0,0 @@ - -#include "tchar.h" -#include "windows.h" -#include "Node.h" -_TCHAR* concat(_TCHAR *str, _TCHAR c); -void copyx( _TCHAR* dst ,_TCHAR* src, int start, int stop); -void voidstr(_TCHAR* str); \ No newline at end of file
tinku99/ahkdll
bec97a33554e22cd1092b32d01b0fd12c992f70c
removed bifs
diff --git a/source/script.cpp b/source/script.cpp index badd978..15cb3fb 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -517,1025 +517,1027 @@ ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestar // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef _USRDLL //Ignore errors since mostly AutoHotkey.exe alredy registered the class RegisterClassEx(&wc); #else if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif // _USRDLL #endif // MINIDLL TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) { if (MyAddClipboardListener && MyRemoveClipboardListener) // Should be impossible for only one of these to be NULL, but check both anyway to be safe. { // The old clipboard viewer chain method is prone to break when some other application uses // it incorrectly. This newer method should be more reliable, but requires Vista or later: MyAddClipboardListener(g_hWnd); // But this method doesn't appear to send an initial WM_CLIPBOARDUPDATE message. // For consistency with the other method (below) and for backward compatibility, // run the OnClipboardChange label once when the script first starts: PostMessage(g_hWnd, AHK_CLIPBOARD_CHANGE, 0, 0); } else mNextClipboardViewer = SetClipboardViewer(g_hWnd); } return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if ( !(g_array = (global_struct *)malloc((g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // Check if an exception has been thrown if (g->ThrownToken) // Display an error message ExecUntil_result = g_script.UnhandledException(g->ThrownToken, g->ExcptLine); // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "background thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT); return OK; } #ifndef MINIDLL ResultType Script::Edit() { #ifdef AUTOHOTKEYSC return OK; // Do nothing. #else // This is here in case a compiled script ever uses the Edit command. Since the "Edit This // Script" menu item is not available for compiled scripts, it can't be called from there. TitleMatchModes old_mode = g->TitleMatchMode; g->TitleMatchMode = FIND_ANYWHERE; HWND hwnd = WinExist(*g, mFileName, _T(""), mMainWindowTitle, _T("")); // Exclude our own main window. g->TitleMatchMode = old_mode; if (hwnd) { TCHAR class_name[32]; GetClassName(hwnd, class_name, _countof(class_name)); if (!_tcscmp(class_name, _T("#32770")) || !_tcsnicmp(class_name, _T("AutoHotkey"), 10)) // MessageBox(), InputBox(), FileSelectFile(), or GUI/script-owned window. hwnd = NULL; // Exclude it from consideration. } if (hwnd) // File appears to already be open for editing, so use the current window. SetForegroundWindowEx(hwnd); else { TCHAR buf[MAX_PATH * 2]; // Enclose in double quotes anything that might contain spaces since the CreateProcess() // method, which is attempted first, is more likely to succeed. This is because it uses // the command line method of creating the process, with everything all lumped together: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) // Since this didn't work, try notepad. { // v1.0.40.06: Try to open .ini files first with their associated editor rather than trying the // "edit" verb on them: LPTSTR file_ext; if ( !(file_ext = _tcsrchr(mFileName, '.')) || _tcsicmp(file_ext, _T(".ini")) || !ActionExec(_T("open"), buf, mFileDir, false) ) // Relies on short-circuit boolean order. { // Even though notepad properly handles filenames with spaces in them under WinXP, // even without double quotes around them, it seems safer and more correct to always // enclose the filename in double quotes for maximum compatibility with all OSes: if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) MsgBox(_T("Could not open script.")); // Short message since so rare. } } } return OK; #endif } #endif // MINIDLL ResultType Script::Reload(bool aDisplayErrors) { // The new instance we're about to start will tell our process to stop, or it will display // a syntax error or some other error, in which case our process will still be running: #ifdef _USRDLL reloadDll(); return EARLY_RETURN; #else #ifdef AUTOHOTKEYSC // This is here in case a compiled script ever uses the Reload command. Since the "Reload This // Script" menu item is not available for compiled scripts, it can't be called from there. return g_script.ActionExec(mOurEXE, _T("/restart"), g_WorkingDirOrig, aDisplayErrors); #else TCHAR arg_string[MAX_PATH + 512]; sntprintf(arg_string, _countof(arg_string), _T("/restart \"%s\""), mFileSpec); return g_script.ActionExec(mOurEXE, arg_string, g_WorkingDirOrig, aDisplayErrors); #endif // AUTOHOTKEYSC #endif // _USRDLL } ResultType Script::ExitApp(ExitReasons aExitReason, LPTSTR aBuf, int aExitCode) // Normal exit (if aBuf is NULL), or a way to exit immediately on error (which is mostly // for times when it would be unsafe to call MsgBox() due to the possibility that it would // make the situation even worse). { mExitReason = aExitReason; bool terminate_afterward = aBuf && !*aBuf; if (aBuf && *aBuf) { TCHAR buf[1024]; // No more than size-1 chars will be written and string will be terminated: sntprintf(buf, _countof(buf), _T("Critical Error: %s\n\n") WILL_EXIT, aBuf); // To avoid chance of more errors, don't use MsgBox(): - MessageBox(g_hWnd, buf, g_script.mFileSpec, MB_OK | MB_SETFOREGROUND | MB_APPLMODAL); + // MessageBox(g_hWnd, buf, g_script.mFileSpec, MB_OK | MB_SETFOREGROUND | MB_APPLMODAL); + _fputts(buf, stdout); + _fputts(g_script.mFileSpec, stdout); TerminateApp(aExitReason, CRITICAL_ERROR); // Only after the above. } // Otherwise, it's not a critical error. Note that currently, mOnExitLabel can only be // non-NULL if the script is in a runnable state (since registering an OnExit label requires // that a script command has executed to do it). If this ever changes, the !mIsReadyToExecute // condition should be added to the below if statement: static bool sExitLabelIsRunning = false; if (!mOnExitLabel || sExitLabelIsRunning) // || !mIsReadyToExecute { // In the case of sExitLabelIsRunning == true: // There is another instance of this function beneath us on the stack. Since we have // been called, this is a true exit condition and we exit immediately. // MUST NOT create a new thread when sExitLabelIsRunning because g_array allows only one // extra thread for ExitApp() (which allows it to run even when MAX_THREADS_EMERGENCY has // been reached). See TOTAL_ADDITIONAL_THREADS. g_AllowInterruption = FALSE; // In case TerminateApp releases objects and indirectly causes g->IsPaused = false; // more script to be executed. TerminateApp(aExitReason, aExitCode); } // Otherwise, the script contains the special RunOnExit label that we will run here instead // of exiting. And since it does, we know that the script is in a ready-to-execute state // because that is the only way an OnExit label could have been defined in the first place. // Usually, the RunOnExit subroutine will contain an Exit or ExitApp statement // which results in a recursive call to this function, but this is not required (e.g. the // Exit subroutine could display an "Are you sure?" prompt, and if the user chooses "No", // the Exit sequence can be aborted by simply not calling ExitApp and letting the thread // we create below end normally). // Next, save the current state of the globals so that they can be restored just prior // to returning to our caller: TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); // Save caller's errorlevel. InitNewThread(0, true, true, ACT_INVALID); // Uninterruptibility is handled below. Since this special thread should always run, no checking of g_MaxThreadsTotal is done before calling this. // Turn on uninterruptibility to forbid any hotkeys, timers, or user defined menu items // to interrupt. This is mainly done for peace-of-mind (since possible interactions due to // interruptions have not been studied) and the fact that this most users would not want this // subroutine to be interruptible (it usually runs quickly anyway). Another reason to make // it non-interruptible is that some OnExit subroutines might destruct things used by the // script's hotkeys/timers/menu items, and activating these items during the deconstruction // would not be safe. Finally, if a logoff or shutdown is occurring, it seems best to prevent // timed subroutines from running -- which might take too much time and prevent the exit from // occurring in a timely fashion. An option can be added via the FutureUse param to make it // interruptible if there is ever a demand for that. // UPDATE: g_AllowInterruption is now used instead of g->AllowThreadToBeInterrupted for two reasons: // 1) It avoids the need to do "int mUninterruptedLineCountMax_prev = g_script.mUninterruptedLineCountMax;" // (Disable this item so that ExecUntil() won't automatically make our new thread uninterruptible // after it has executed a certain number of lines). // 2) Mostly obsolete: If the thread we're interrupting is uninterruptible, the uninterruptible timer // might be currently pending. When it fires, it would make the OnExit subroutine interruptible // rather than the underlying subroutine. The above fixes the first part of that problem. // The 2nd part is fixed by reinstating the timer when the uninterruptible thread is resumed. // This special handling is only necessary here -- not in other places where new threads are // created -- because OnExit is the only type of thread that can interrupt an uninterruptible // thread. BOOL g_AllowInterruption_prev = g_AllowInterruption; // Save current setting. g_AllowInterruption = FALSE; // Mark the thread just created above as permanently uninterruptible (i.e. until it finishes and is destroyed). sExitLabelIsRunning = true; DEBUGGER_STACK_PUSH(mOnExitLabel->mJumpToLine, mOnExitLabel->mName) if (mOnExitLabel->Execute() == FAIL) { // If the subroutine encounters a failure condition such as a runtime error, exit immediately. // Otherwise, there will be no way to exit the script if the subroutine fails on each attempt. TerminateApp(aExitReason, aExitCode); } DEBUGGER_STACK_POP() sExitLabelIsRunning = false; // In case the user wanted the thread to end normally (see above). if (terminate_afterward) TerminateApp(aExitReason, aExitCode); // Otherwise: ResumeUnderlyingThread(ErrorLevel_saved); g_AllowInterruption = g_AllowInterruption_prev; // Restore original setting. return EARLY_EXIT; } void Script::TerminateApp(ExitReasons aExitReason, int aExitCode) // Note that g_script's destructor takes care of most other cleanup work, such as destroying // tray icons, menus, and unowned windows such as ToolTip. { #ifdef _USRDLL terminateDll(); #else // L31: Release objects stored in variables, where possible. if (aExitCode != CRITICAL_ERROR) // i.e. Avoid making matters worse if CRITICAL_ERROR. { int v, i; for (v = 0; v < mVarCount; ++v) if (mVar[v]->IsObject()) mVar[v]->ReleaseObject(); for (v = 0; v < mLazyVarCount; ++v) if (mLazyVar[v]->IsObject()) mLazyVar[v]->ReleaseObject(); for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) if (f.mVar[v]->IsStatic() && f.mVar[v]->IsObject()) // For consistency, only free static vars (see above). f.mVar[v]->ReleaseObject(); for (v = 0; v < f.mLazyVarCount; ++v) if (f.mLazyVar[v]->IsStatic() && f.mLazyVar[v]->IsObject()) f.mLazyVar[v]->ReleaseObject(); } } #ifdef CONFIG_DEBUGGER // L34: Exit debugger *after* the above to allow debugging of any invoked __Delete handlers. g_Debugger.Exit(aExitReason); #endif // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } Hotkey::AllDestructAndExit(aExitCode); #endif } #ifndef AUTOHOTKEYSC LineNumberType Script::LoadFromText(LPTSTR aScript) // HotKeyIt H1 LoadFromText() for text instead LoadFromFile() // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedText(aScript) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { #ifndef MINIDLL // Check for any unprocessed #if expressions: for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < mFuncCount; ++i) { Func &func = *mFunc[i]; if (!func.mIsBuiltIn) { PreprocessLocalVars(func, func.mVar, func.mVarCount); PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above calls. // Use FindOrAdd, not Add, because the user may already have added it simply by // referring to it in the script: if ( !(g_ErrorLevel = FindOrAddVar(_T("ErrorLevel"))) ) return LOADING_FAILED; // Error. Above already displayed it for us. // Initialize the var state to zero right before running anything in the script: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Initialize the random number generator: // Note: On 32-bit hardware, the generator module uses only 2506 bytes of static // data, so it doesn't seem worthwhile to put it in a class (so that the mem is // only allocated on first use of the generator). For v1.0.24, _ftime() is not // used since it could be as large as 0.5 KB of non-compressed code. A simple call to // GetSystemTimeAsFileTime() seems just as good or better, since it produces // a FILETIME, which is "the number of 100-nanosecond intervals since January 1, 1601." // Use the low-order DWORD since the high-order one rarely changes. If my calculations are correct, // the low-order 32-bits traverses its full 32-bit range every 7.2 minutes, which seems to make // using it as a seed superior to GetTickCount for most purposes. RESEED_RANDOM_GENERATOR; return TRUE; // Must be non-zero. // OBSOLETE: mLineCount was always non-zero at this point since above did AddLine(). //return mLineCount; // The count of runnable lines that were loaded, which might be zero. } #endif #ifdef AUTOHOTKEYSC UINT Script::LoadFromFile() #else UINT Script::LoadFromFile(bool aScriptWasNotspecified) #endif // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; if (!mFileSpec || !*mFileSpec) return LOADING_FAILED; #ifndef AUTOHOTKEYSC // When not in stand-alone mode, read an external script file. DWORD attr = GetFileAttributes(mFileSpec); if (attr == MAXDWORD && !g_hResource) // File does not exist or lacking the authorization to get its attributes. { #ifdef MINIDLL return LOADING_FAILED; #endif TCHAR buf[MAX_PATH + 256]; if (aScriptWasNotspecified) // v1.0.46.09: Give a more descriptive prompt to help users get started. { sntprintf(buf, _countof(buf), _T("To help you get started, would you like to create a sample script in the My Documents folder?\n") _T("\n") _T("Press YES to create and display the sample script.\n") _T("Press NO to exit.\n")); } else // Mostly for backward compatibility, also prompt to create if an explicitly specified script doesn't exist. sntprintf(buf, _countof(buf), _T("The script file \"%s\" does not exist. Create it now?"), mFileSpec); int response = MsgBox(buf, MB_YESNO); if (response != IDYES) return 0; FILE *fp2 = _tfopen(mFileSpec, _T("a")); if (!fp2) { MsgBox(_T("Could not create file, perhaps because the current directory is read-only") _T(" or has insufficient permissions.")); return LOADING_FAILED; } _fputts( _T("; IMPORTANT INFO ABOUT GETTING STARTED: Lines that start with a\n") _T("; semicolon, such as this one, are comments. They are not executed.\n") _T("\n") _T("; This script has a special filename and path because it is automatically\n") _T("; launched when you run the program directly. Also, any text file whose\n") _T("; name ends in .ahk is associated with the program, which means that it\n") _T("; can be launched simply by double-clicking it. You can have as many .ahk\n") _T("; files as you want, located in any folder. You can also run more than\n") _T("; one .ahk file simultaneously and each will get its own tray icon.\n") _T("\n") _T("; SAMPLE HOTKEYS: Below are two sample hotkeys. The first is Win+Z and it\n") _T("; launches a web site in the default browser. The second is Control+Alt+N\n") _T("; and it launches a new Notepad window (or activates an existing one). To\n") _T("; try out these hotkeys, run AutoHotkey again, which will load this file.\n") _T("\n") _T("#z::Run www.autohotkey.com\n") _T("\n") _T("^!n::\n") _T("IfWinExist Untitled - Notepad\n") _T("\tWinActivate\n") _T("else\n") _T("\tRun Notepad\n") _T("return\n") _T("\n") _T("\n") _T("; Note: From now on whenever you run AutoHotkey directly, this script\n") _T("; will be loaded. So feel free to customize it to suit your needs.\n") _T("\n") _T("; Please read the QUICK-START TUTORIAL near the top of the help file.\n") _T("; It explains how to perform common automation tasks such as sending\n") _T("; keystrokes and mouse clicks. It also explains more about hotkeys.\n") , fp2); fclose(fp2); // One or both of the below would probably fail -- at least on Win95 -- if mFileSpec ever // has spaces in it (since it's passed as the entire param string). So enclose the filename // in double quotes. I don't believe the directory needs to be in double quotes since it's // a separate field within the CreateProcess() and ShellExecute() structures: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) { MsgBox(_T("Can't open script.")); // Short msg since so rare. return LOADING_FAILED; } // future: have it wait for the process to close, then try to open the script again: return 0; } #endif // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedFile(mFileSpec, false, false) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { // Check for any unprocessed #if expressions: #ifndef MINIDLL for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < mFuncCount; ++i) { Func &func = *mFunc[i]; if (!func.mIsBuiltIn) { PreprocessLocalVars(func, func.mVar, func.mVarCount); PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". @@ -9097,1523 +9099,1533 @@ ResultType Script::DefineClassVars(LPTSTR aBuf, bool aStatic) *item_end = '\0'; // Temporarily terminate. if (class_object->GetItem(temp_token, item)) return ScriptError(ERR_DUPLICATE_DECLARATION, item); // Assigning class_object[item] := "" is sufficient to mark it as a class variable: if (!class_object->SetItem(item, aStatic ? empty_token : int_token)) return ScriptError(ERR_OUTOFMEM); *item_end = orig_char; // Undo termination. size_t name_length = item_end - item; // This section is very similar to the on in ParseAndAddLine() which deals with // variable declarations, so maybe maintain them together: item_end = omit_leading_whitespace(item_end); // Move up to the next comma, assignment-op, or '\0'. switch (*item_end) { case ',': // No initializer is present for this variable, so move on to the next one. item = omit_leading_whitespace(item_end + 1); // Set "item" for use by the next iteration. continue; // No further processing needed below. case '\0': // No initializer is present for this variable, so move on to the next one. item = item_end; // Set "item" for use by the loop's condition. continue; case '=': // Supported for consistency with v1 syntax; to be removed in v2. ++item_end; // Point to the character after the "=". break; case ':': if (item_end[1] == '=') { item_end += 2; // Point to the character after the ":=". break; } // Otherwise, fall through to below: default: return ScriptError(ERR_INVALID_CLASS_VAR, item); } // Since above didn't "continue", this declared variable also has an initializer. // Append the class name, ":=" and initializer to pending_buf, to be turned into // an expression below, and executed at script start-up. item_end = omit_leading_whitespace(item_end); LPTSTR right_side_of_operator = item_end; // Save for use below. item_end += FindNextDelimiter(item_end); // Find the next comma which is not part of the initializer (or find end of string). // Append "ClassNameOrThis.VarName := Initializer, " to the buffer. int chars_written = _sntprintf(buf + buf_used, _countof(buf) - buf_used, _T("%s.%.*s := %.*s, ") , aStatic ? mClassName : _T("this"), name_length, item, item_end - right_side_of_operator, right_side_of_operator); if (chars_written < 0) return ScriptError(_T("Declaration too long.")); // Short message since should be rare. buf_used += chars_written; // Set "item" for use by the next iteration: item = (*item_end == ',') // i.e. it's not the terminator and thus not the final item in the list. ? omit_leading_whitespace(item_end + 1) : item_end; // It's the terminator, so let the loop detect that to finish. } if (buf_used) { // Above wrote at least one initializer expression into buf. buf[buf_used -= 2] = '\0'; // Remove the final ", " // The following section temporarily replaces mLastLine in order to insert script lines // either at the end of the list of static initializers (separate from the main script) // or at the end of the __Init method belonging to this class. Save the current values: Line *script_first_line = mFirstLine, *script_last_line = mLastLine; Line *block_end; Func *init_func = NULL; if (aStatic) { mLastLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } else { ExprTokenType token; if (class_object->GetItem(token, _T("__Init")) && token.symbol == SYM_OBJECT && (init_func = dynamic_cast<Func *>(token.object))) // This cast SHOULD always succeed; done for maintainability. { // __Init method already exists, so find the end of its body. for (block_end = init_func->mJumpToLine; block_end->mActionType != ACT_BLOCK_END || !block_end->mAttribute; block_end = block_end->mNextLine); } else { // Create an __Init method for this class. TCHAR def[] = _T("__Init()"); if (!DefineFunc(def, NULL) || !AddLine(ACT_BLOCK_BEGIN) || (class_object->Base() && !ParseAndAddLine(_T("base.__Init()"), ACT_EXPRESSION))) // Initialize base-class variables first. Relies on short-circuit evaluation. return FAIL; mLastLine->mLineNumber = 0; // Signal the debugger to skip this line while stepping in/over/out. init_func = g->CurrentFunc; init_func->mDefaultVarType = VAR_DECLARE_GLOBAL; // Allow global variables/class names in initializer expressions. if (!AddLine(ACT_BLOCK_END)) // This also resets g->CurrentFunc to NULL. return FAIL; block_end = mLastLine; block_end->mLineNumber = 0; // See above. // These must be updated as one or both have changed: script_first_line = mFirstLine; script_last_line = mLastLine; } g->CurrentFunc = init_func; // g->CurrentFunc should be NULL prior to this. mLastLine = block_end->mPrevLine; // i.e. insert before block_end. mLastLine->mNextLine = NULL; // For maintainability; AddLine() should overwrite it regardless. } if (!ParseAndAddLine(buf, ACT_EXPRESSION)) return FAIL; // Above already displayed the error. if (aStatic) { if (!mFirstStaticLine) mFirstStaticLine = mLastLine; mLastStaticLine = mLastLine; // The following is necessary if there weren't any executable lines above this static // initializer (i.e. mFirstLine was NULL and has been set to the newly created line): mFirstLine = script_first_line; } else { if (init_func->mJumpToLine == block_end) // This can be true only for the first initializer of a class with no base-class. init_func->mJumpToLine = mLastLine; // Rejoin the function's block-end (and any lines following it) to the main script. mLastLine->mNextLine = block_end; block_end->mPrevLine = mLastLine; // mFirstLine should be left as it is: if it was NULL, it now contains a pointer to our // __init function's block-begin, which is now the very first executable line in the script. g->CurrentFunc = NULL; } // Restore mLastLine so that any subsequent script lines are added at the correct point. mLastLine = script_last_line; } return OK; } Object *Script::FindClass(LPCTSTR aClassName, size_t aClassNameLength) { if (!aClassNameLength) aClassNameLength = _tcslen(aClassName); if (!aClassNameLength || aClassNameLength > MAX_CLASS_NAME_LENGTH) return NULL; LPTSTR cp, key; ExprTokenType token; Object *base_object = NULL; TCHAR class_name[MAX_CLASS_NAME_LENGTH + 2]; // Extra +1 for '.' to simplify parsing. // Make temporary copy which we can modify. tmemcpy(class_name, aClassName, aClassNameLength); class_name[aClassNameLength] = '.'; // To simplify parsing. class_name[aClassNameLength + 1] = '\0'; // Get base variable; e.g. "MyClass" in "MyClass.MySubClass". cp = _tcschr(class_name + 1, '.'); Var *base_var = FindVar(class_name, cp - class_name, NULL, FINDVAR_GLOBAL); if (!base_var) return NULL; // Although at load time only the "Object" type can exist, dynamic_cast is used in case we're called at run-time: if ( !(base_var->IsObject() && (base_object = dynamic_cast<Object *>(base_var->Object()))) ) return NULL; // Even if the loop below has no iterations, it initializes 'key' to the appropriate value: for (key = cp + 1; cp = _tcschr(key, '.'); key = cp + 1) // For each key in something like TypeVar.Key1.Key2. { if (cp == key) return NULL; // ScriptError(_T("Missing name."), cp); *cp = '\0'; // Terminate at the delimiting dot. if (!base_object->GetItem(token, key)) return NULL; base_object = (Object *)token.object; // See comment about Object() above. } return base_object; } #ifndef AUTOHOTKEYSC struct FuncLibrary { LPTSTR path; DWORD_PTR length; }; Func *Script::FindFuncInLibrary(LPTSTR aFuncName, size_t aFuncNameLength, bool &aErrorWasShown, bool &aFileWasFound, bool aIsAutoInclude) // Caller must ensure that aFuncName doesn't already exist as a defined function. // If aFuncNameLength is 0, the entire length of aFuncName is used. { aErrorWasShown = false; // Set default for this output parameter. aFileWasFound = false; int i; LPTSTR char_after_last_backslash, terminate_here; TCHAR buf[MAX_PATH+1]; DWORD attr; #define FUNC_LIB_EXT _T(".ahk") #define FUNC_LIB_EXT_LENGTH (_countof(FUNC_LIB_EXT) - 1) #define FUNC_LOCAL_LIB _T("\\Lib\\") // Needs leading and trailing backslash. #define FUNC_LOCAL_LIB_LENGTH (_countof(FUNC_LOCAL_LIB) - 1) #define FUNC_USER_LIB _T("\\AutoHotkey\\Lib\\") // Needs leading and trailing backslash. #define FUNC_USER_LIB_LENGTH (_countof(FUNC_USER_LIB) - 1) #define FUNC_STD_LIB _T("Lib\\") // Needs trailing but not leading backslash. #define FUNC_STD_LIB_LENGTH (_countof(FUNC_STD_LIB) - 1) #define FUNC_LIB_COUNT 4 static FuncLibrary sLib[FUNC_LIB_COUNT] = {0}; if (!sLib[0].path) // Allocate & discover paths only upon first use because many scripts won't use anything from the library. This saves a bit of memory and performance. { for (i = 0; i < FUNC_LIB_COUNT; ++i) if ( !(sLib[i].path = (LPTSTR) SimpleHeap::Malloc(MAX_PATH * sizeof(TCHAR))) ) // Need MAX_PATH for to allow room for appending each candidate file/function name. return NULL; // Due to rarity, simply pass the failure back to caller. FuncLibrary *this_lib; // DETERMINE PATH TO "LOCAL" LIBRARY: this_lib = sLib; // For convenience and maintainability. this_lib->length = BIV_ScriptDir(NULL, _T("")); if (this_lib->length < MAX_PATH-FUNC_LOCAL_LIB_LENGTH) { this_lib->length = BIV_ScriptDir(this_lib->path, _T("")); _tcscpy(this_lib->path + this_lib->length, FUNC_LOCAL_LIB); this_lib->length += FUNC_LOCAL_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "USER" LIBRARY: this_lib++; // For convenience and maintainability. this_lib->length = BIV_MyDocuments(this_lib->path, _T("")); if (this_lib->length < MAX_PATH-FUNC_USER_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_USER_LIB); this_lib->length += FUNC_USER_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "STANDARD" LIBRARY: this_lib++; // For convenience and maintainability. GetModuleFileName(NULL, this_lib->path, MAX_PATH); // The full path to the currently-running AutoHotkey.exe. char_after_last_backslash = 1 + _tcsrchr(this_lib->path, '\\'); // Should always be found, so failure isn't checked. this_lib->length = (DWORD)(char_after_last_backslash - this_lib->path); // The length up to and including the last backslash. if (this_lib->length < MAX_PATH-FUNC_STD_LIB_LENGTH) { _tcscpy(this_lib->path + this_lib->length, FUNC_STD_LIB); this_lib->length += FUNC_STD_LIB_LENGTH; } else // Insufficient room to build the path name. { *this_lib->path = '\0'; // Mark this library as disabled. this_lib->length = 0; // } // DETERMINE PATH TO "AHKPATH\Lib.lnk" LIBRARY: this_lib++; // For convenience and maintainability. BIV_AhkPath(this_lib->path, _T("")); _tcscpy(_tcsrchr(this_lib->path,'\\')+1,_T("Lib.lnk")); *(_tcsrchr(this_lib->path,'\\')+8) = '\0'; CoInitialize(NULL); IShellLink *psl; if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) { #ifdef UNICODE if (SUCCEEDED(ppf->Load(this_lib->path, 0))) #else WCHAR wsz[MAX_PATH+1]; // +1 hasn't been explained, but is retained in case it's needed. ToWideChar(this_lib->path, wsz, MAX_PATH+1); // Dest. size is in wchars, not bytes. if (SUCCEEDED(ppf->Load((const WCHAR*)wsz, 0))) #endif { TCHAR buf[MAX_PATH+1]; psl->GetPath(buf, MAX_PATH, NULL, SLGP_UNCPRIORITY); _tcscpy(this_lib->path,buf); _tcscpy(this_lib->path + _tcslen(buf),_T("\\\0")); } ppf->Release(); } psl->Release(); } CoUninitialize(); if ( !_tcsrchr(FileAttribToStr(buf, GetFileAttributes(this_lib->path)),'D') ) { this_lib->length = 0; *this_lib->path = '\0'; } else this_lib->length = _tcslen(this_lib->path); for (i = 0; i < FUNC_LIB_COUNT; ++i) { attr = GetFileAttributes(sLib[i].path); // Seems to accept directories that have a trailing backslash, which is good because it simplifies the code. if (attr == 0xFFFFFFFF || !(attr & FILE_ATTRIBUTE_DIRECTORY)) // Directory doesn't exist or it's a file vs. directory. Relies on short-circuit boolean order. { *sLib[i].path = '\0'; // Mark this library as disabled. sLib[i].length = 0; // } } } // Above must ensure that all sLib[].path elements are non-NULL (but they can be "" to indicate "no library"). if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); TCHAR *dest, *first_underscore, class_name_buf[MAX_VAR_NAME_LENGTH + 1]; LPTSTR naked_filename = aFuncName; // Set up for the first iteration. size_t naked_filename_length = aFuncNameLength; // for (int second_iteration = 0; second_iteration < 2; ++second_iteration) { for (i = 0; i < FUNC_LIB_COUNT; ++i) { if (!*sLib[i].path) // Library is marked disabled, so skip it. continue; if (sLib[i].length + naked_filename_length >= MAX_PATH-FUNC_LIB_EXT_LENGTH) continue; // Path too long to match in this library, but try others. dest = (LPTSTR) tmemcpy(sLib[i].path + sLib[i].length, naked_filename, naked_filename_length); // Append the filename to the library path. _tcscpy(dest + naked_filename_length, FUNC_LIB_EXT); // Append the file extension. attr = GetFileAttributes(sLib[i].path); // Testing confirms that GetFileAttributes() doesn't support wildcards; which is good because we want filenames containing question marks to be "not found" rather than being treated as a match-pattern. if (attr == 0xFFFFFFFF || (attr & FILE_ATTRIBUTE_DIRECTORY)) // File doesn't exist or it's a directory. Relies on short-circuit boolean order. continue; aFileWasFound = true; // Indicate success for #include <lib>, which doesn't necessarily expect a function to be found. // Since above didn't "continue", a file exists whose name matches that of the requested function. // Before loading/including that file, set the working directory to its folder so that if it uses // #Include, it will be able to use more convenient/intuitive relative paths. This is similar to // the "#Include DirName" feature. // Call SetWorkingDir() vs. SetCurrentDirectory() so that it succeeds even for a root drive like // C: that lacks a backslash (see SetWorkingDir() for details). terminate_here = sLib[i].path + sLib[i].length - 1; // The trailing backslash in the full-path-name to this library. *terminate_here = '\0'; // Temporarily terminate it for use with SetWorkingDir(). SetWorkingDir(sLib[i].path); // See similar section in the #Include directive. *terminate_here = '\\'; // Undo the termination. if (mIncludeLibraryFunctionsThenExit && aIsAutoInclude) { // For each auto-included library-file, write out two #Include lines: // 1) Use #Include in its "change working directory" mode so that any explicit #include directives // or FileInstalls inside the library file itself will work consistently and properly. // 2) Use #IncludeAgain (to improve performance since no dupe-checking is needed) to include // the library file itself. // We don't directly append library files onto the main script here because: // 1) ahk2exe needs to be able to see and act upon FileInstall and #Include lines (i.e. library files // might contain #Include even though it's rare). // 2) #IncludeAgain and #Include directives that bring in fragments rather than entire functions or // subroutines wouldn't work properly if we resolved such includes in AutoHotkey.exe because they // wouldn't be properly interleaved/asynchronous, but instead brought out of their library file // and deposited separately/synchronously into the temp-include file by some new logic at the // AutoHotkey.exe's code for the #Include directive. // 3) ahk2exe prefers to omit comments from included files to minimize size of compiled scripts. mIncludeLibraryFunctionsThenExit->Format(_T("#Include %-0.*s\n#IncludeAgain %s\n") , sLib[i].length, sLib[i].path, sLib[i].path); // Now continue on normally so that our caller can continue looking for syntax errors. } // Fix for v1.1.06.00: If the file contains any lib #includes, it must be loaded AFTER the // above writes sLib[i].path to the iLib file, otherwise the wrong filename could be written. if (!LoadIncludedFile(sLib[i].path, false, false)) // Fix for v1.0.47.05: Pass false for allow-dupe because otherwise, it's possible for a stdlib file to attempt to include itself (especially via the LibNamePrefix_ method) and thus give a misleading "duplicate function" vs. "func does not exist" error message. Obsolete: For performance, pass true for allow-dupe so that it doesn't have to check for a duplicate file (seems too rare to worry about duplicates since by definition, the function doesn't yet exist so it's file shouldn't yet be included). { aErrorWasShown = true; // Above has just displayed its error (e.g. syntax error in a line, failed to open the include file, etc). So override the default set earlier. return NULL; } // Now that a matching filename has been found, it seems best to stop searching here even if that // file doesn't actually contain the requested function. This helps library authors catch bugs/typos. return FindFunc(aFuncName, aFuncNameLength); } // for() each library directory. // Now that the first iteration is done, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. break; // All loops are done because second iteration is the last possible attempt. naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). break; // All loops are done because second iteration is the last possible attempt. naked_filename = class_name_buf; // Point it to a buffer for use below. tmemcpy(naked_filename, aFuncName, naked_filename_length); naked_filename[naked_filename_length] = '\0'; } // 2-iteration for(). // HotKeyIt find library in Resource // Since above didn't return, no match found in any library. // Search in Resource for a library tmemcpy(class_name_buf, aFuncName, aFuncNameLength); tmemcpy(class_name_buf + aFuncNameLength,_T(".ahk"),4); class_name_buf[aFuncNameLength + 4] = '\0'; HRSRC lib_hResource; if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) { // Now that the resource is not found, set up for the second one that searches by class/prefix. // Notes about ambiguity and naming collisions: // By the time it gets to the prefix/class search, it's almost given up. Even if it wrongly finds a // match in a filename that isn't really a class, it seems inconsequential because at worst it will // still not find the function and will then say "call to nonexistent function". In addition, the // ability to customize which libraries are searched is planned. This would allow a publicly // distributed script to turn off all libraries except stdlib. if ( !(first_underscore = _tcschr(aFuncName, '_')) ) // No second iteration needed. return NULL; naked_filename_length = first_underscore - aFuncName; if (naked_filename_length >= _countof(class_name_buf)) // Class name too long (probably impossible currently). return NULL; tmemcpy(class_name_buf, aFuncName, naked_filename_length); tmemcpy(class_name_buf + naked_filename_length,_T(".ahk"),4); class_name_buf[naked_filename_length + 4] = '\0'; if (!(lib_hResource = FindResource(g_hInstance, class_name_buf, _T("LIB")))) return NULL; } // Now a resouce was found and it can be loaded HGLOBAL hResData; TextMem::Buffer textbuf(NULL, 0, false); if ( !( (textbuf.mLength = SizeofResource(g_hInstance, lib_hResource)) && (hResData = LoadResource(g_hInstance, lib_hResource)) && (textbuf.mBuffer = LockResource(hResData)) ) ) { // aErrorWasShown = true; // Do not display errors here return NULL; } aFileWasFound = true; // NOTE: Ahk2Exe strips off the UTF-8 BOM. TextMem tmem; LPTSTR resource_script = (LPTSTR)_alloca(textbuf.mLength * sizeof(TCHAR)); tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF8); tmem.Read(resource_script, textbuf.mLength); if (!LoadIncludedText(resource_script)) { aFileWasFound = false; return NULL; } else { return FindFunc(aFuncName, aFuncNameLength); } } #endif Func *Script::FindFunc(LPCTSTR aFuncName, size_t aFuncNameLength, int *apInsertPos) // L27: Added apInsertPos for binary-search. // Returns the Function whose name matches aFuncName (which caller has ensured isn't NULL). // If it doesn't exist, NULL is returned. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (apInsertPos) // L27: Set default for maintainability. *apInsertPos = -1; // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. If the caller later // tries to add the function, it will get an error then: if (aFuncNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the name searching to use _tcsicmp() instead of // strlicmp(), which close to doubles the performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // +1 to convert length to size. Func *pfunc; // Using a binary searchable array vs a linked list speeds up dynamic function calls, on average. int left, right, mid, result; for (left = 0, right = mFuncCount - 1; left <= right;) { mid = (left + right) / 2; result = _tcsicmp(func_name, mFunc[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return mFunc[mid]; } if (apInsertPos) *apInsertPos = left; // Since above didn't return, there is no match. See if it's a built-in function that hasn't yet // been added to the function list. // Set defaults to be possibly overridden below: int min_params = 1; int max_params = 1; BuiltInFunctionType bif; LPTSTR suffix = func_name + 3; #ifndef MINIDLL + /* if (!_tcsnicmp(func_name, _T("LV_"), 3)) // As a built-in function, LV_* can only be a ListView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("GetNext"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("GetCount"))) { bif = BIF_LV_GetNextOrCount; min_params = 0; // But leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("GetText"))) { bif = BIF_LV_GetText; min_params = 2; max_params = 3; } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_LV_AddInsertModify; min_params = 0; // 0 params means append a blank row. max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Insert"))) { bif = BIF_LV_AddInsertModify; // Leave min_params at 1. Passing only 1 param to it means "insert a blank row". max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_LV_AddInsertModify; // Although it shares the same function with "Insert", it can still have its own min/max params. min_params = 2; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_LV_Delete; min_params = 0; // Leave max at its default of 1. } else if (!_tcsicmp(suffix, _T("InsertCol"))) { bif = BIF_LV_InsertModifyDeleteCol; // Leave min_params at 1 because inserting a blank column ahead of the first column // does not seem useful enough to sacrifice the no-parameter mode, which might have // potential future uses. max_params = 3; } else if (!_tcsicmp(suffix, _T("ModifyCol"))) { bif = BIF_LV_InsertModifyDeleteCol; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("DeleteCol"))) bif = BIF_LV_InsertModifyDeleteCol; // Leave min/max set to 1. else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_LV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("TV_"), 3)) // As a built-in function, TV_* can only be a TreeView function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // Leave min at its default of 1. } else if (!_tcsicmp(suffix, _T("Modify"))) { bif = BIF_TV_AddModifyDelete; max_params = 3; // One-parameter mode is "select specified item". } else if (!_tcsicmp(suffix, _T("Delete"))) { bif = BIF_TV_AddModifyDelete; min_params = 0; } else if (!_tcsicmp(suffix, _T("GetParent")) || !_tcsicmp(suffix, _T("GetChild")) || !_tcsicmp(suffix, _T("GetPrev"))) bif = BIF_TV_GetRelatedItem; else if (!_tcsicmp(suffix, _T("GetCount")) || !_tcsicmp(suffix, _T("GetSelection"))) { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 0; } else if (!_tcsicmp(suffix, _T("GetNext"))) // Unlike "Prev", Next also supports 0 or 2 parameters. { bif = BIF_TV_GetRelatedItem; min_params = 0; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get")) || !_tcsicmp(suffix, _T("GetText"))) { bif = BIF_TV_Get; min_params = 2; max_params = 2; } else if (!_tcsicmp(suffix, _T("SetImageList"))) { bif = BIF_TV_SetImageList; max_params = 2; // Leave min at 1. } else return NULL; } else if (!_tcsnicmp(func_name, _T("IL_"), 3)) // It's an ImageList function. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_IL_Create; min_params = 0; max_params = 3; } else if (!_tcsicmp(suffix, _T("Destroy"))) { bif = BIF_IL_Destroy; // Leave Min/Max set to 1. } else if (!_tcsicmp(suffix, _T("Add"))) { bif = BIF_IL_Add; min_params = 2; max_params = 4; } else return NULL; } else if (!_tcsicmp(func_name, _T("SB_SetText"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } else if (!_tcsicmp(func_name, _T("SB_SetParts"))) { bif = BIF_StatusBar; min_params = 0; max_params = 255; // 255 params allows for up to 256 parts, which is SB's max. } else if (!_tcsicmp(func_name, _T("SB_SetIcon"))) { bif = BIF_StatusBar; max_params = 3; // Leave min_params at its default of 1. } - else if (!_tcsicmp(func_name, _T("StrLen"))) + */ + if (!_tcsicmp(func_name, _T("StrLen"))) #else if (!_tcsicmp(func_name, _T("StrLen"))) #endif bif = BIF_StrLen; else if (!_tcsicmp(func_name, _T("SubStr"))) { bif = BIF_SubStr; min_params = 2; max_params = 3; } - else if (!_tcsicmp(func_name, _T("Lock"))) + /* else if (!_tcsicmp(func_name, _T("Lock"))) { bif = BIF_Lock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CriticalObject"))) { bif = BIF_CriticalObject; min_params = 0; max_params = 2; } else if (!_tcsicmp(func_name, _T("TryLock"))) { bif = BIF_TryLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("UnLock"))) { bif = BIF_UnLock; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindFunc"))) // addFile() Naveen v8. { bif = BIF_FindFunc; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("FindLabel"))) // HotKeyIt v1.1.02.00 { bif = BIF_FindLabel; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Static"))) // lowlevel() Naveen v9. { bif = BIF_Static; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Alias"))) // lowlevel() Naveen v9. { bif = BIF_Alias; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("getTokenValue"))) // lowlevel() Naveen v9. { bif = BIF_getTokenValue; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("CacheEnable"))) // lowlevel() Naveen v9. { bif = BIF_CacheEnable; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("Getvar"))) // lowlevel() Naveen v9. { bif = BIF_Getvar; min_params = 1; max_params = 1; } + */ else if (!_tcsicmp(func_name, _T("Trim")) || !_tcsicmp(func_name, _T("LTrim")) || !_tcsicmp(func_name, _T("RTrim"))) // L31 { bif = BIF_Trim; min_params = 1; max_params = 2; } else if (!_tcsicmp(func_name, _T("InStr"))) { bif = BIF_InStr; min_params = 2; max_params = 5; } else if (!_tcsicmp(func_name, _T("RegExMatch"))) { bif = BIF_RegEx; min_params = 2; max_params = 4; } else if (!_tcsicmp(func_name, _T("RegExReplace"))) { bif = BIF_RegEx; min_params = 2; max_params = 6; } - else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) + /* else if (!_tcsnicmp(func_name, _T("GetKey"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("State"))) { bif = BIF_GetKeyState; max_params = 2; } else if (!_tcsicmp(suffix, _T("Name")) || !_tcsicmp(suffix, _T("VK")) || !_tcsicmp(suffix, _T("SC"))) bif = BIF_GetKeyName; else return NULL; - } + } */ else if (!_tcsicmp(func_name, _T("Asc"))) bif = BIF_Asc; else if (!_tcsicmp(func_name, _T("Chr"))) bif = BIF_Chr; - else if (!_tcsicmp(func_name, _T("StrGet"))) + /* else if (!_tcsicmp(func_name, _T("StrGet"))) { bif = BIF_StrGetPut; max_params = 3; } else if (!_tcsicmp(func_name, _T("StrPut"))) { bif = BIF_StrGetPut; max_params = 4; } else if (!_tcsicmp(func_name, _T("NumGet"))) { bif = BIF_NumGet; max_params = 3; } else if (!_tcsicmp(func_name, _T("NumPut"))) { bif = BIF_NumPut; min_params = 2; max_params = 4; - } + } else if (!_tcsicmp(func_name, _T("IsLabel"))) bif = BIF_IsLabel; + */ else if (!_tcsicmp(func_name, _T("Func"))) bif = BIF_Func; else if (!_tcsicmp(func_name, _T("IsFunc"))) bif = BIF_IsFunc; else if (!_tcsicmp(func_name, _T("IsByRef"))) bif = BIF_IsByRef; + /* #ifdef ENABLE_DLLCALL else if (!_tcsicmp(func_name, _T("DllCall"))) { bif = BIF_DllCall; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } #endif else if (!_tcsicmp(func_name, _T("ResourceLoadLibrary"))) { bif = BIF_ResourceLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryLoadLibrary"))) { bif = BIF_MemoryLoadLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("MemoryGetProcAddress"))) { bif = BIF_MemoryGetProcAddress; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("MemoryFreeLibrary"))) { bif = BIF_MemoryFreeLibrary; min_params = 1; max_params = 1; } else if (!_tcsicmp(func_name, _T("DynaCall"))) { bif = BIF_DynaCall; min_params = 0; max_params = 10000; // An arbitrarily high limit that will never realistically be reached. } else if (!_tcsicmp(func_name, _T("VarSetCapacity"))) { bif = BIF_VarSetCapacity; max_params = 3; } + else if (!_tcsicmp(func_name, _T("FileExist"))) bif = BIF_FileExist; else if (!_tcsicmp(func_name, _T("WinExist")) || !_tcsicmp(func_name, _T("WinActive"))) { bif = BIF_WinExistActive; min_params = 0; max_params = 4; } + */ else if (!_tcsicmp(func_name, _T("Round"))) { bif = BIF_Round; max_params = 2; } else if (!_tcsicmp(func_name, _T("Floor")) || !_tcsicmp(func_name, _T("Ceil"))) bif = BIF_FloorCeil; else if (!_tcsicmp(func_name, _T("Mod"))) { bif = BIF_Mod; min_params = 2; max_params = 2; } else if (!_tcsicmp(func_name, _T("Abs"))) bif = BIF_Abs; else if (!_tcsicmp(func_name, _T("Sin"))) bif = BIF_Sin; else if (!_tcsicmp(func_name, _T("Cos"))) bif = BIF_Cos; else if (!_tcsicmp(func_name, _T("Tan"))) bif = BIF_Tan; else if (!_tcsicmp(func_name, _T("ASin")) || !_tcsicmp(func_name, _T("ACos"))) bif = BIF_ASinACos; else if (!_tcsicmp(func_name, _T("ATan"))) bif = BIF_ATan; else if (!_tcsicmp(func_name, _T("Exp"))) bif = BIF_Exp; else if (!_tcsicmp(func_name, _T("Sqrt")) || !_tcsicmp(func_name, _T("Log")) || !_tcsicmp(func_name, _T("Ln"))) bif = BIF_SqrtLogLn; - else if (!_tcsicmp(func_name, _T("OnMessage"))) + /* else if (!_tcsicmp(func_name, _T("OnMessage"))) { bif = BIF_OnMessage; max_params = 3; // Leave min at 1. // By design, scripts that use OnMessage are persistent by default. Doing this here // also allows WinMain() to later detect whether this script should become #SingleInstance. // Note: Don't directly change g_AllowOnlyOneInstance here in case the remainder of the // script-loading process comes across any explicit uses of #SingleInstance, which would // override the default set here. g_persistent = true; } #ifdef ENABLE_REGISTERCALLBACK else if (!_tcsicmp(func_name, _T("RegisterCallback"))) { bif = BIF_RegisterCallback; max_params = 4; // Leave min_params at 1. } #endif + */ else if (!_tcsicmp(func_name, _T("IsObject"))) // L31 { bif = BIF_IsObject; max_params = 10000; // Leave min_params at 1. } else if (!_tcsnicmp(func_name, _T("Obj"), 3)) // L31: See script_object.cpp for details. { suffix = func_name + 3; if (!_tcsicmp(suffix, _T("ect"))) // i.e. "Object" { bif = BIF_ObjCreate; min_params = 0; max_params = 10000; } #define BIF_OBJ_CASE(aCaseSuffix, aMinParams, aMaxParams) \ else if (!_tcsicmp(suffix, _T(#aCaseSuffix))) \ { \ bif = BIF_Obj##aCaseSuffix; \ min_params = (1 + aMinParams); \ max_params = (1 + aMaxParams); \ } // All of these functions require the "object" parameter, // but it is excluded from the counts below for clarity: BIF_OBJ_CASE(Insert, 1, 10000) // [key,] value [, value2, ...] BIF_OBJ_CASE(Remove, 0, 2) // [min_key, max_key] BIF_OBJ_CASE(MinIndex, 0, 0) BIF_OBJ_CASE(MaxIndex, 0, 0) BIF_OBJ_CASE(HasKey, 1, 1) // key BIF_OBJ_CASE(GetCapacity, 0, 1) // [key] BIF_OBJ_CASE(SetCapacity, 1, 2) // [key,] new_capacity BIF_OBJ_CASE(GetAddress, 1, 1) // key BIF_OBJ_CASE(NewEnum, 0, 0) BIF_OBJ_CASE(Clone, 0, 0) #undef BIF_OBJ_CASE else if (!_tcsicmp(suffix, _T("AddRef")) || !_tcsicmp(suffix, _T("Release"))) bif = BIF_ObjAddRefRelease; else return NULL; } else if (!_tcsicmp(func_name, _T("Array"))) { bif = BIF_ObjArray; min_params = 0; max_params = 10000; } - else if (!_tcsicmp(func_name, _T("FileOpen"))) + /* else if (!_tcsicmp(func_name, _T("FileOpen"))) { bif = BIF_FileOpen; min_params = 2; max_params = 3; } + else if (!_tcsnicmp(func_name, _T("ComObj"), 6)) { suffix = func_name + 6; if (!_tcsicmp(suffix, _T("Create"))) { bif = BIF_ComObjCreate; max_params = 2; } else if (!_tcsicmp(suffix, _T("Get"))) bif = BIF_ComObjGet; else if (!_tcsicmp(suffix, _T("Connect"))) { bif = BIF_ComObjConnect; max_params = 2; } else if (!_tcsicmp(suffix, _T("Error"))) { bif = BIF_ComObjError; min_params = 0; } else if (!_tcsicmp(suffix, _T("Type"))) { bif = BIF_ComObjTypeOrValue; max_params = 2; } else if (!_tcsicmp(suffix, _T("Value"))) { bif = BIF_ComObjTypeOrValue; } else if (!_tcsicmp(suffix, _T("Flags"))) { bif = BIF_ComObjFlags; max_params = 3; } else if (!_tcsicmp(suffix, _T("Array"))) { bif = BIF_ComObjArray; min_params = 2; max_params = 9; // up to 8 dimensions } else if (!_tcsicmp(suffix, _T("Query"))) { bif = BIF_ComObjQuery; min_params = 2; max_params = 3; } else { bif = BIF_ComObjActive; min_params = 0; max_params = 3; } } + */ else if (!_tcsicmp(func_name, _T("Exception"))) { bif = BIF_Exception; max_params = 3; } else return NULL; // Maint: There may be other lines above that also return NULL. // Since above didn't return, this is a built-in function that hasn't yet been added to the list. // Add it now: if ( !(pfunc = AddFunc(func_name, aFuncNameLength, true, left)) ) // L27: left contains the position within mFunc to insert the function. Cannot use *apInsertPos as caller may have omitted it or passed NULL. return NULL; pfunc->mBIF = bif; pfunc->mMinParams = min_params; pfunc->mParamCount = max_params; return pfunc; } Func *Script::AddFunc(LPCTSTR aFuncName, size_t aFuncNameLength, bool aIsBuiltIn, int aInsertPos, Object *aClassObject) // This function should probably not be called by anyone except FindOrAddFunc, which has already done // the dupe-checking. // Returns the address of the new function or NULL on failure. // The caller must already have verified that this isn't a duplicate function. { if (!aFuncNameLength) // Caller didn't specify, so use the entire string. aFuncNameLength = _tcslen(aFuncName); if (aFuncNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Function name too long."), aFuncName); return NULL; } // Make a temporary copy that includes only the first aFuncNameLength characters from aFuncName: TCHAR func_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(func_name, aFuncName, aFuncNameLength + 1); // See explanation above. +1 to convert length to size. // In the future, it might be best to add another check here to disallow function names that consist // entirely of numbers. However, this hasn't been done yet because: // 1) Not sure if there will ever be a good enough reason. // 2) Even if it's done in the far future, it won't break many scripts (pure-numeric functions should be very rare). // 3) Those scripts that are broken are not broken in a bad way because the pre-parser will generate a // load-time error, which is easy to fix (unlike runtime errors, which require that part of the script // to actually execute). if (!aClassObject && !Var::ValidateName(func_name, DISPLAY_FUNC_ERROR)) // Variable and function names are both validated the same way. // Above already displayed error for us. This can happen at loadtime or runtime (e.g. StringSplit). return NULL; // Allocate some dynamic memory to pass to the constructor: LPTSTR new_name = SimpleHeap::Malloc(func_name, aFuncNameLength); if (!new_name) // It already displayed the error for us. return NULL; Func *the_new_func = new Func(new_name, aIsBuiltIn); if (!the_new_func) { ScriptError(ERR_OUTOFMEM); return NULL; } if (aClassObject) { LPTSTR key = _tcsrchr(new_name, '.'); if (!key) { ScriptError(_T("Invalid method name."), new_name); // Shouldn't ever happen. return NULL; } if (!aClassObject->SetItem(key + 1, the_new_func)) { ScriptError(ERR_OUTOFMEM); return NULL; } // Also add it to the script's list of functions, to support #Warn LocalSameAsGlobal // and automatic cleanup of objects in static vars on program exit. } if (mFuncCount == mFuncCountMax) { // Allocate or expand function list. int alloc_count = mFuncCountMax ? mFuncCountMax * 2 : 100; Func **temp = (Func **)realloc(mFunc, alloc_count * sizeof(Func *)); // If passed NULL, realloc() will do a malloc(). if (!temp) { ScriptError(ERR_OUTOFMEM); return NULL; } mFunc = temp; mFuncCountMax = alloc_count; } if (aInsertPos != mFuncCount) // Need to make room at the indicated position for this variable. memmove(mFunc + aInsertPos + 1, mFunc + aInsertPos, (mFuncCount - aInsertPos) * sizeof(Func *)); //else both are zero or the item is being inserted at the end of the list, so it's easy. mFunc[aInsertPos] = the_new_func; ++mFuncCount; return the_new_func; } size_t Line::ArgIndexLength(int aArgIndex) // This function is similar to ArgToInt(), so maintain them together. // "ArgLength" is the arg's fully resolved, dereferenced length during runtime. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. // ArgLength() was added in v1.0.44.14 to help its callers improve performance by avoiding // costly calls to _tcslen() (which is especially beneficial for huge strings). { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // Arg doesn't exist, so don't try accessing sArgVar (unlike sArgDeref, it wouldn't be valid to do so). return 0; // i.e. treat it as the empty string. // The length is not known and must be calculated in the following situations: // - The arg consists of more than just a single isolated variable name (not possible if the arg is // ARG_TYPE_INPUT_VAR). // - The arg is a built-in variable, in which case the length isn't known, so it must be derived from // the string copied into sArgDeref[] by an earlier stage. // - The arg is a normal variable but it's VAR_ATTRIB_BINARY_CLIP. In such cases, our callers do not // recognize/support binary-clipboard as binary and want the apparent length of the string returned // (i.e. _tcslen(), which takes into account the position of the first binary zero wherever it may be). if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; // For performance and convenience. if ( var.Type() == VAR_NORMAL // This and below ordered for short-circuit performance based on types of input expected from caller. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) // Although the ones that have the highbit set are hereby omitted from the fast method, the nature of almost all of the highbit commands is such that their performance won't be measurably affected. See ArgMustBeDereferenced() for more info. && (g_NoEnv || var.HasContents()) // v1.0.46.02: Recognize environment variables (when g_NoEnv==FALSE) by falling through to _tcslen() for them. && &var != g_ErrorLevel ) // Mostly for maintainability because the following situation is very rare: If it's g_ErrorLevel, use the deref version instead because if g_ErrorLevel is an input variable in the caller's command, and the caller changes ErrorLevel (such as to set a default) prior to calling this function, the changed/new ErrorLevel will be used rather than its original value (which is usually undesirable). //&& !var.IsBinaryClip()) // This check isn't necessary because the line below handles it. return var.LengthIgnoreBinaryClip(); // Do it the fast way (unless it's binary clipboard, in which case this call will internally call _tcslen()). } // Otherwise, length isn't known due to no variable, a built-in variable, or an environment variable. // So do it the slow way. return _tcslen(sArgDeref[aArgIndex]); } __int64 Line::ArgIndexToInt64(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0; // i.e. treat it as ATOI64(""). // SEE THIS POSITION IN ArgIndexLength() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToInt64(FALSE); } // Otherwise: return ATOI64(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } double Line::ArgIndexToDouble(int aArgIndex) // This function is similar to ArgIndexLength(), so maintain them together. // Callers must call this only at times when sArgDeref and sArgVar are defined/meaningful. // Caller must ensure that aArgIndex is 0 or greater. { #ifdef _DEBUG if (aArgIndex < 0) { LineError(_T("DEBUG: BAD"), WARN); aArgIndex = 0; // But let it continue. } #endif if (aArgIndex >= mArgc) // See ArgIndexLength() for comments. return 0.0; // i.e. treat it as ATOF(""). // SEE THIS POSITION IN ARGLENGTH() FOR IMPORTANT COMMENTS ABOUT THE BELOW. if (sArgVar[aArgIndex]) { Var &var = *sArgVar[aArgIndex]; if ( var.Type() == VAR_NORMAL // See ArgIndexLength() for comments about this line and below. && !(g_act[mActionType].MaxParamsAu2WithHighBit & 0x80) && (g_NoEnv || var.HasContents()) && &var != g_ErrorLevel && !var.IsBinaryClip() ) return var.ToDouble(FALSE); } // Otherwise: return ATOF(sArgDeref[aArgIndex]); // See ArgIndexLength() for comments. } Var *Line::ResolveVarOfArg(int aArgIndex, bool aCreateIfNecessary) // Returns NULL on failure. Caller has ensured that none of this arg's derefs are function-calls. // Args that are input or output variables are normally resolved at load-time, so that // they contain a pointer to their Var object. This is done for performance. However, // in order to support dynamically resolved variables names like AutoIt2 (e.g. arrays), // we have to do some extra work here at runtime. // Callers specify false for aCreateIfNecessary whenever the contents of the variable // they're trying to find is unimportant. For example, dynamically built input variables, // such as "StringLen, length, array%i%", do not need to be created if they weren't // previously assigned to (i.e. they weren't previously used as an output variable). // In the above example, the array element would never be created here. But if the output // variable were dynamic, our call would have told us to create it. { // The requested ARG isn't even present, so it can't have a variable. Currently, this should // never happen because the loading procedure ensures that input/output args are not marked // as variables if they are blank (and our caller should check for this and not call in that case): if (aArgIndex >= mArgc) return NULL; ArgStruct &this_arg = mArg[aArgIndex]; // For performance and convenience. // Since this function isn't inline (since it's called so frequently), there isn't that much more // overhead to doing this check, even though it shouldn't be needed since it's the caller's // responsibility: if (this_arg.type == ARG_TYPE_NORMAL) // Arg isn't an input or output variable. return NULL; if (!*this_arg.text) // The arg's variable is not one that needs to be dynamically resolved. return VAR(this_arg); // Return the var's address that was already determined at load-time. // The above might return NULL in the case where the arg is optional (i.e. the command allows // the var name to be omitted). But in that case, the caller should either never have called this // function or should check for NULL upon return. UPDATE: This actually never happens, see // comment above the "if (aArgIndex >= mArgc)" line. // Static to correspond to the static empty_var further below. It needs the memory area // to support resolving dynamic environment variables. In the following example, // the result will be blank unless the first line is present (without this fix here): //null = %SystemRoot% ; bogus line as a required workaround in versions prior to v1.0.16 //thing = SystemRoot //StringTrimLeft, output, %thing%, 0 //msgbox %output% static TCHAR sVarName[MAX_VAR_NAME_LENGTH + 1]; // Will hold the dynamically built name. // At this point, we know the requested arg is a variable that must be dynamically resolved. // This section is similar to that in ExpandArg(), so they should be maintained together: LPTSTR pText = this_arg.text; // Start at the beginning of this arg's text. size_t var_name_length = 0; if (this_arg.deref) // There's at least one deref. { // Caller has ensured that none of these derefs are function calls (i.e. deref->is_function is alway false). for (DerefType *deref = this_arg.deref // Start off by looking for the first deref. ; deref->marker; ++deref) // A deref with a NULL marker terminates the list. { // FOR EACH DEREF IN AN ARG (if we're here, there's at least one): // Copy the chars that occur prior to deref->marker into the buffer: for (; pText < deref->marker && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && pText < deref->marker) // The variable name would be too long! { // This type of error is just a warning because this function isn't set up to cause a true // failure. This is because the use of dynamically named variables is rare, and only for // people who should know what they're doing. In any case, when the caller of this // function called it to resolve an output variable, it will see the the result is // NULL and terminate the current subroutine. #define DYNAMIC_TOO_LONG _T("This dynamically built variable name is too long.") \ _T(" If this variable was not intended to be dynamic, remove the % symbols from it.") LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } // Now copy the contents of the dereferenced var. For all cases, aBuf has already // been verified to be large enough, assuming the value hasn't changed between the // time we were called and the time the caller calculated the space needed. if (deref->var->Get() > (VarSizeType)(MAX_VAR_NAME_LENGTH - var_name_length)) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } var_name_length += deref->var->Get(sVarName + var_name_length); // Finally, jump over the dereference text. Note that in the case of an expression, there might not // be any percent signs within the text of the dereference, e.g. x + y, not %x% + %y%. pText += deref->length; } } // Copy any chars that occur after the final deref into the buffer: for (; *pText && var_name_length < MAX_VAR_NAME_LENGTH; sVarName[var_name_length++] = *pText++); if (var_name_length >= MAX_VAR_NAME_LENGTH && *pText) // The variable name would be too long! { LineError(DYNAMIC_TOO_LONG, FAIL, this_arg.text); return NULL; } if (!var_name_length) { LineError(_T("This dynamic variable is blank. If this variable was not intended to be dynamic,") _T(" remove the % symbols from it."), FAIL, this_arg.text); return NULL; } // Terminate the buffer, even if nothing was written into it: sVarName[var_name_length] = '\0'; static Var empty_var(sVarName, (void *)VAR_NORMAL, false); // Must use sVarName here. See comment above for why. Var *found_var; if (!aCreateIfNecessary) { // Now we've dynamically build the variable name. It's possible that the name is illegal, // so check that (the name is automatically checked by FindOrAddVar(), so we only need to // check it if we're not calling that): if (!Var::ValidateName(sVarName)) return NULL; // Above already displayed error for us. if (found_var = g_script.FindVar(sVarName, var_name_length)) // Assign. return found_var; // At this point, this is either a non-existent variable or a reserved/built-in variable // that was never statically referenced in the script (only dynamically), e.g. A_IPAddress%A_Index% if (Script::GetVarType(sVarName) == (void *)VAR_NORMAL) // If not found: for performance reasons, don't create it because caller just wants an empty variable. return &empty_var; //else it's the clipboard or some other built-in variable, so continue onward so that the // variable gets created in the variable list, which is necessary to allow it to be properly // dereferenced, e.g. in a script consisting of only the following: // Loop, 4 // StringTrimRight, IP, A_IPAddress%A_Index%, 0 } // Otherwise, aCreateIfNecessary is true or we want to create this variable unconditionally for the // reason described above. if ( !(found_var = g_script.FindOrAddVar(sVarName, var_name_length)) ) return NULL; // Above will already have displayed the error. if (this_arg.type == ARG_TYPE_OUTPUT_VAR && VAR_IS_READONLY(*found_var)) { LineError(ERR_VAR_IS_READONLY, FAIL, sVarName); return NULL; // Don't return the var, preventing the caller from assigning to it. } else return found_var; } Var *Script::FindOrAddVar(LPTSTR aVarName, size_t aVarNameLength, int aScope) // Caller has ensured that aVarName isn't NULL. // Returns the Var whose name matches aVarName. If it doesn't exist, it is created. { if (!*aVarName) return NULL; int insert_pos; bool is_local; // Used to detect which type of var should be added in case the result of the below is NULL. Var *var; if (var = FindVar(aVarName, aVarNameLength, &insert_pos, aScope, &is_local)) return var; // Otherwise, no match found, so create a new var. This will return NULL if there was a problem, // in which case AddVar() will already have displayed the error: return AddVar(aVarName, aVarNameLength, insert_pos , (aScope & ~(VAR_LOCAL | VAR_GLOBAL)) | (is_local ? VAR_LOCAL : VAR_GLOBAL)); // When aScope == FINDVAR_DEFAULT, it contains both the "local" and "global" bits. This ensures only the appropriate bit is set. } Var *Script::FindVar(LPTSTR aVarName, size_t aVarNameLength, int *apInsertPos, int aScope , bool *apIsLocal) // Caller has ensured that aVarName isn't NULL. It must also ignore the contents of apInsertPos when // a match (non-NULL value) is returned. // Returns the Var whose name matches aVarName. If it doesn't exist, NULL is returned. // If caller provided a non-NULL apInsertPos, it will be given a the array index that a newly // inserted item should have to keep the list in sorted order (which also allows the ListVars command // to display the variables in alphabetical order). { if (!*aVarName) return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); // For the below, no error is reported because callers don't want that. Instead, simply return // NULL to indicate that names that are illegal or too long are not found. When the caller later // tries to add the variable, it will get an error then: if (aVarNameLength > MAX_VAR_NAME_LENGTH) return NULL; // The following copy is made because it allows the various searches below to use _tcsicmp() instead of // strlicmp(), which close to doubles their performance. The copy includes only the first aVarNameLength // characters from aVarName: TCHAR var_name[MAX_VAR_NAME_LENGTH + 1]; tcslcpy(var_name, aVarName, aVarNameLength + 1); // +1 to convert length to size. global_struct &g = *::g; // Reduces code size and may improve performance. bool search_local = (aScope & VAR_LOCAL) && g.CurrentFunc; // Above has ensured that g.CurrentFunc!=NULL whenever search_local==true. // Init for binary search loop: int left, right, mid, result; // left/right must be ints to allow them to go negative and detect underflow. Var **var; // An array of pointers-to-var. if (search_local) { var = g.CurrentFunc->mVar; right = g.CurrentFunc->mVarCount - 1; } else { var = mVar; right = mVarCount - 1; } // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } // Since above didn't return, no match was found in the main list, so search the lazy list if there // is one. If there's no lazy list, the value of "left" established above will be used as the // insertion point further below: if (search_local) { var = g.CurrentFunc->mLazyVar; right = g.CurrentFunc->mLazyVarCount - 1; } else { var = mLazyVar; right = mLazyVarCount - 1; } if (var) // There is a lazy list to search (and even if the list is empty, left must be reset to 0 below). { // Binary search: for (left = 0; left <= right;) // "right" was already initialized above. { mid = (left + right) / 2; result = _tcsicmp(var_name, var[mid]->mName); // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. if (result > 0) left = mid + 1; else if (result < 0) right = mid - 1; else // Match found. return var[mid]; } } // Since above didn't return, no match was found and "left" always contains the position where aVarName // should be inserted to keep the list sorted. The item is always inserted into the lazy list unless // there is no lazy list. // Set the output parameter, if present: if (apInsertPos) // Caller wants this value even if we'll be resorting to searching the global list below. *apInsertPos = left; // This is the index a newly inserted item should have to keep alphabetical order. if (apIsLocal) // Its purpose is to inform caller of type it would have been in case we don't find a match. *apIsLocal = search_local; // Since no match was found, if this is a local fall back to searching the list of globals at runtime // if the caller didn't insist on a particular type: if (search_local && aScope == FINDVAR_DEFAULT) { // In this case, callers want to fall back to globals when a local wasn't found. However, // they want the insertion (if our caller will be doing one) to insert according to the // current assume-mode. Therefore, if the mode is assume-global, pass the apIsLocal // and apInsertPos variables to FindVar() so that it will update them to be global. if (g.CurrentFunc->mDefaultVarType == VAR_DECLARE_GLOBAL) return FindVar(aVarName, aVarNameLength, apInsertPos, FINDVAR_GLOBAL, apIsLocal); // v1: Each *dynamic* variable reference may resolve to a global if one exists. if (mIsReadyToExecute) return FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL); // Otherwise, caller only wants globals which are declared in *this* function: for (int i = 0; i < g.CurrentFunc->mGlobalVarCount; ++i) if (!_tcsicmp(var_name, g.CurrentFunc->mGlobalVar[i]->mName)) // lstrcmpi() is not used: 1) avoids breaking existing scripts; 2) provides consistent behavior across multiple locales; 3) performance. return g.CurrentFunc->mGlobalVar[i]; // As a last resort, check for a super-global: Var *gvar = FindVar(aVarName, aVarNameLength, NULL, FINDVAR_GLOBAL, NULL); if (gvar && gvar->IsSuperGlobal()) return gvar; } // Otherwise, since above didn't return: return NULL; // No match. } Var *Script::AddVar(LPTSTR aVarName, size_t aVarNameLength, int aInsertPos, int aScope) // Returns the address of the new variable or NULL on failure. // Caller must ensure that g->CurrentFunc!=NULL whenever aIsLocal!=0. // Caller must ensure that aVarName isn't NULL and that this isn't a duplicate variable name. // In addition, it has provided aInsertPos, which is the insertion point so that the list stays sorted. // Finally, aIsLocal has been provided to indicate which list, global or local, should receive this // new variable, as well as the type of local variable. (See the declaration of VAR_LOCAL etc.) { if (!*aVarName) // Should never happen, so just silently indicate failure. return NULL; if (!aVarNameLength) // Caller didn't specify, so use the entire string. aVarNameLength = _tcslen(aVarName); if (aVarNameLength > MAX_VAR_NAME_LENGTH) { ScriptError(_T("Variable name too long."), aVarName); @@ -17162,1285 +17174,1287 @@ __forceinline ResultType Line::Perform() // As of 2/9/2009, __forceinline() redu // so caller called it wrong. ACT_INVALID should be impossible because // Script::AddLine() forbids it. #ifdef _DEBUG return LineError(_T("DEBUG: Perform(): Unhandled action type.")); #else return FAIL; #endif } ResultType Line::Deref(Var *aOutputVar, LPTSTR aBuf) // Similar to ExpandArg(), except it parses and expands all variable references contained in aBuf. { aOutputVar = aOutputVar->ResolveAlias(); // Necessary for proper detection below of whether it's invalidly used as a source for itself. // This transient variable is used resolving environment variables that don't already exist // in the script's variable list (due to the fact that they aren't directly referenced elsewhere // in the script): TCHAR var_name[MAX_VAR_NAME_LENGTH + 1] = _T(""); Var *var; VarSizeType expanded_length; size_t var_name_length; LPTSTR cp, cp1, dest; // Do two passes: // #1: Calculate the space needed so that aOutputVar can be given more capacity if necessary. // #2: Expand the contents of aBuf into aOutputVar. for (int which_pass = 0; which_pass < 2; ++which_pass) { if (which_pass) // Starting second pass. { // Set up aOutputVar, enlarging it if necessary. If it is of type VAR_CLIPBOARD, // this call will set up the clipboard for writing: if (aOutputVar->AssignString(NULL, expanded_length) != OK) return FAIL; dest = aOutputVar->Contents(); // Init, and for performance. } else // First pass. expanded_length = 0; // Init prior to accumulation. for (cp = aBuf; ; ++cp) // Increment to skip over the deref/escape just found by the inner for(). { // Find the next escape char or deref symbol: for (; *cp && *cp != g_EscapeChar && *cp != g_DerefChar; ++cp) { if (which_pass) // 2nd pass *dest++ = *cp; // Copy all non-variable-ref characters literally. else // just accumulate the length ++expanded_length; } if (!*cp) // End of string while scanning/copying. The current pass is now complete. break; if (*cp == g_EscapeChar) { if (which_pass) // 2nd pass { cp1 = cp + 1; switch (*cp1) // See ConvertEscapeSequences() for more details. { // Only lowercase is recognized for these: case 'a': *dest = '\a'; break; // alert (bell) character case 'b': *dest = '\b'; break; // backspace case 'f': *dest = '\f'; break; // formfeed case 'n': *dest = '\n'; break; // newline case 'r': *dest = '\r'; break; // carriage return case 't': *dest = '\t'; break; // horizontal tab case 'v': *dest = '\v'; break; // vertical tab default: *dest = *cp1; // These other characters are resolved just as they are, including '\0'. } ++dest; } else ++expanded_length; // Increment cp here and it will be incremented again by the outer loop, i.e. +2. // In other words, skip over the escape character, treating it and its target character // as a single character. ++cp; continue; } // Otherwise, it's a dereference symbol, so calculate the size of that variable's contents // and add that to expanded_length (or copy the contents into aOutputVar if this is the // second pass). // Find the reference's ending symbol (don't bother with catching escaped deref chars here // -- e.g. %MyVar`% -- since it seems too troublesome to justify given how extremely rarely // it would be an issue): for (cp1 = cp + 1; *cp1 && *cp1 != g_DerefChar; ++cp1); if (!*cp1) // Since end of string was found, this deref is not correctly terminated. continue; // For consistency, omit it entirely. var_name_length = cp1 - cp - 1; if (var_name_length && var_name_length <= MAX_VAR_NAME_LENGTH) { tcslcpy(var_name, cp + 1, var_name_length + 1); // +1 to convert var_name_length to size. // Fixed for v1.0.34: Use FindOrAddVar() vs. FindVar() so that environment or built-in // variables that aren't directly referenced elsewhere in the script will still work: if ( !(var = g_script.FindOrAddVar(var_name, var_name_length)) ) return FAIL; // Above already displayed the error. var = var->ResolveAlias(); // Don't allow the output variable to be read into itself this way because its contents if (var != aOutputVar) // Both of these have had ResolveAlias() called, if required, to make the comparison accurate. { if (which_pass) // 2nd pass dest += var->Get(dest); else // just accumulate the length expanded_length += var->Get(); // Add in the length of the variable's contents. } } // else since the variable name between the deref symbols is blank or too long: for consistency in behavior, // it seems best to omit the dereference entirely (don't put it into aOutputVar). cp = cp1; // For the next loop iteration, continue at the char after this reference's final deref symbol. } // for() } // for() (first and second passes) *dest = '\0'; // Terminate the output variable. aOutputVar->SetCharLength((VarSizeType)_tcslen(aOutputVar->Contents())); // Update to actual in case estimate was too large. return aOutputVar->Close(); // In case it's the clipboard. } LPTSTR Line::LogToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates sLog into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. // Caller has ensured that aBuf is non-NULL and that aBufSize is reasonable (at least 256). { LPTSTR aBuf_orig = aBuf; // Store the position of where each retry done by the outer loop will start writing: LPTSTR aBuf_log_start = aBuf + sntprintf(aBuf, aBufSize, _T("Script lines most recently executed (oldest first).") _T(" Press [F5] to refresh. The seconds elapsed between a line and the one after it is in parentheses to") _T(" the right (if not 0). The bottommost line's elapsed time is the number of seconds since it executed.\r\n\r\n")); int i, lines_to_show, line_index, line_index2, space_remaining; // space_remaining must be an int to detect negatives. #ifndef AUTOHOTKEYSC int last_file_index = -1; #endif DWORD elapsed; bool this_item_is_special, next_item_is_special; // In the below, sLogNext causes it to start at the oldest logged line and continue up through the newest: for (lines_to_show = LINE_LOG_SIZE, line_index = sLogNext;;) // Retry with fewer lines in case the first attempt doesn't fit in the buffer. { aBuf = aBuf_log_start; // Reset target position in buffer to the place where log should begin. for (next_item_is_special = false, i = 0; i < lines_to_show; ++i, ++line_index) { if (line_index >= LINE_LOG_SIZE) // wrap around, because sLog is a circular queue line_index -= LINE_LOG_SIZE; // Don't just reset it to zero because an offset larger than one may have been added to it. if (!sLog[line_index]) // No line has yet been logged in this slot. continue; // ACT_LISTLINES and other things might rely on "continue" isntead of halting the loop here. this_item_is_special = next_item_is_special; next_item_is_special = false; // Set default. if (i + 1 < lines_to_show) // There are still more lines to be processed { if (this_item_is_special) // And we know from the above that this special line is not the last line. // Due to the fact that these special lines are usually only useful when they appear at the // very end of the log, omit them from the log-display when they're not the last line. // In the case of a high-frequency SetTimer, this greatly reduces the log clutter that // would otherwise occur: continue; // Since above didn't continue, this item isn't special, so display it normally. elapsed = sLogTick[line_index + 1 >= LINE_LOG_SIZE ? 0 : line_index + 1] - sLogTick[line_index]; if (elapsed > INT_MAX) // INT_MAX is about one-half of DWORD's capacity. { // v1.0.30.02: Assume that huge values (greater than 24 days or so) were caused by // the new policy of storing WinWait/RunWait/etc.'s line in the buffer whenever // it was interrupted and later resumed by a thread. In other words, there are now // extra lines in the buffer which are considered "special" because they don't indicate // a line that actually executed, but rather one that is still executing (waiting). // See ACT_WINWAIT for details. next_item_is_special = true; // Override the default. if (i + 2 == lines_to_show) // The line after this one is not only special, but the last one that will be shown, so recalculate this one correctly. elapsed = GetTickCount() - sLogTick[line_index]; else // Neither this line nor the special one that follows it is the last. { // Refer to the line after the next (special) line to get this line's correct elapsed time. line_index2 = line_index + 2; if (line_index2 >= LINE_LOG_SIZE) line_index2 -= LINE_LOG_SIZE; elapsed = sLogTick[line_index2] - sLogTick[line_index]; } } } else // This is the last line (whether special or not), so compare it's time against the current time instead. elapsed = GetTickCount() - sLogTick[line_index]; #ifndef AUTOHOTKEYSC // If the this line and the previous line are in different files, display the filename: if (last_file_index != sLog[line_index]->mFileIndex) { last_file_index = sLog[line_index]->mFileIndex; aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("---- %s\r\n"), sSourceFile[last_file_index]); } #endif space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate really huge lines so that the Edit control's size is less likely to be exhausted. // In v1.0.30.02, this is even more likely due to having increased the line-buf's capacity from // 200 to 400, therefore the truncation point was reduced from 500 to 200 to make it more likely // that the first attempt to fit the lines_to_show number of lines into the buffer will succeed. aBuf = sLog[line_index]->ToText(aBuf, space_remaining < 200 ? space_remaining : 200, true, elapsed, this_item_is_special); // If the line above can't fit everything it needs into the remaining space, it will fill all // of the remaining space, and thus the check against LINE_LOG_FINAL_MESSAGE_LENGTH below // should never fail to catch that, and then do a retry. } // Inner for() #define LINE_LOG_FINAL_MESSAGE _T("\r\nPress [F5] to refresh.") // Keep the next line in sync with this. #define LINE_LOG_FINAL_MESSAGE_LENGTH 24 if (BUF_SPACE_REMAINING > LINE_LOG_FINAL_MESSAGE_LENGTH || lines_to_show < 120) // Either success or can't succeed. break; // Otherwise, there is insufficient room to put everything in, but there's still room to retry // with a smaller value of lines_to_show: lines_to_show -= 100; line_index = sLogNext + (LINE_LOG_SIZE - lines_to_show); // Move the starting point forward in time so that the oldest log entries are omitted. } // outer for() that retries the log-to-buffer routine. // Must add the return value, not LINE_LOG_FINAL_MESSAGE_LENGTH, in case insufficient room (i.e. in case // outer loop terminated due to lines_to_show being too small). return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, LINE_LOG_FINAL_MESSAGE); } LPTSTR Line::VicinityToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 the current line and the lines above and below it into their text equivalent // putting the result into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; #define LINES_ABOVE_AND_BELOW 7 // Determine the correct value for line_start and line_end: int i; Line *line_start, *line_end; for (i = 0, line_start = this ; i < LINES_ABOVE_AND_BELOW && line_start->mPrevLine != NULL ; ++i, line_start = line_start->mPrevLine); for (i = 0, line_end = this ; i < LINES_ABOVE_AND_BELOW && line_end->mNextLine != NULL ; ++i, line_end = line_end->mNextLine); #ifdef AUTOHOTKEYSC if (!g_AllowMainWindow) // Override the above to show only a single line, to conceal the script's source code. { line_start = this; line_end = this; } #endif // Now line_start and line_end are the first and last lines of the range // we want to convert to text, and they're non-NULL. aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\tLine#\n")); int space_remaining; // Must be an int to preserve any negative results. // Start at the oldest and continue up through the newest: for (Line *line = line_start;;) { if (line == this) tcslcpy(aBuf, _T("--->\t"), BUF_SPACE_REMAINING); else tcslcpy(aBuf, _T("\t"), BUF_SPACE_REMAINING); aBuf += _tcslen(aBuf); space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate large lines so that the dialog is more readable: aBuf = line->ToText(aBuf, space_remaining < 500 ? space_remaining : 500, false); if (line == line_end) break; line = line->mNextLine; } return aBuf; } LPTSTR Line::ToText(LPTSTR aBuf, int aBufSize, bool aCRLF, DWORD aElapsed, bool aLineWasResumed) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 line into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. { if (aBufSize < 3) return aBuf; else aBufSize -= (1 + aCRLF); // Reserve one char for LF/CRLF after each line (so that it always get added). LPTSTR aBuf_orig = aBuf; aBuf += sntprintf(aBuf, aBufSize, _T("%03u: "), mLineNumber); if (aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("STILL WAITING (%0.2f): "), (float)aElapsed / 1000.0); if (mActionType == ACT_IFBETWEEN || mActionType == ACT_IFNOTBETWEEN) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("if %s %s %s and %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2, RAW_ARG3); else if (ACT_IS_ASSIGN(mActionType) || (ACT_IS_IF(mActionType) && mActionType < ACT_FIRST_COMMAND)) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s%s %s %s") , ACT_IS_IF(mActionType) ? _T("if ") : _T("") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2); else if (mActionType == ACT_FOR) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("For %s,%s in %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , *mArg[1].text || !VAR(mArg[1]) ? mArg[1].text : VAR(mArg[1])->mName // can be omitted. , mArg[2].text); else { aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s"), g_act[mActionType].Name); for (int i = 0; i < mArgc; ++i) // This method a little more efficient than using snprintfcat(). // Also, always use the arg's text for input and output args whose variables haven't // been resolved at load-time, since the text has everything in it we want to display // and thus there's no need to "resolve" dynamic variables here (e.g. array%i%). aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(",%s"), (mArg[i].type != ARG_TYPE_NORMAL && !*mArg[i].text) ? VAR(mArg[i])->mName : mArg[i].text); } if (aElapsed && !aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" (%0.2f)"), (float)aElapsed / 1000.0); // UPDATE for v1.0.25: It seems that MessageBox(), which is the only way these lines are currently // displayed, prefers \n over \r\n because otherwise, Ctrl-C on the MsgBox copies the lines all // onto one line rather than formatted nicely as separate lines. // Room for LF or CRLF was reserved at the top of this function: if (aCRLF) *aBuf++ = '\r'; *aBuf++ = '\n'; *aBuf = '\0'; return aBuf; } #ifndef MINIDLL void Line::ToggleSuspendState() { // If suspension is being turned on: // It seems unnecessary, and possibly undesirable, to purge any pending hotkey msgs from the msg queue. // Even if there are some, it's possible that they are exempt from suspension so we wouldn't want to // globally purge all messages anyway. g_IsSuspended = !g_IsSuspended; Hotstring::SuspendAll(g_IsSuspended); // Must do this prior to ManifestAllHotkeysHotstringsHooks() to avoid incorrect removal of hook. Hotkey::ManifestAllHotkeysHotstringsHooks(); // Update the state of all hotkeys based on the complex interdependencies hotkeys have with each another. g_script.UpdateTrayIcon(); CheckMenuItem(GetMenu(g_hWnd), ID_FILE_SUSPEND, g_IsSuspended ? MF_CHECKED : MF_UNCHECKED); } #endif void Line::PauseUnderlyingThread(bool aTrueForPauseFalseForUnpause) { if (g <= g_array) // Guard against underflow. This condition can occur when the script thread that called us is the AutoExec section or a callback running in the idle/0 thread. return; if (g[-1].IsPaused == aTrueForPauseFalseForUnpause) // It's already in the right state. return; // Return early because doing the updates further below would be wrong in this case. g[-1].IsPaused = aTrueForPauseFalseForUnpause; // Update the pause state to that specified by caller. if (aTrueForPauseFalseForUnpause) // The underlying thread is being paused when it was unpaused before. ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. else // The underlying thread is being unpaused when it was paused before. --g_nPausedThreads; } ResultType Line::ChangePauseState(ToggleValueType aChangeTo, bool aAlwaysOperateOnUnderlyingThread) // Currently designed to be called only by the Pause command (ACT_PAUSE). // Returns OK or FAIL. { switch (aChangeTo) { case TOGGLED_ON: break; // By breaking instead of returning, pause will be put into effect further below. case TOGGLED_OFF: // v1.0.37.06: The old method was to unpause the the nearest paused thread on the call stack; // but it was flawed because if the thread that made the flag true is interrupted, and the new // thread is paused via the pause command, and that thread is then interrupted, when the paused // thread resumes it would automatically and wrongly be unpaused (i.e. the unpause ticket would // be used at a level higher in the call stack than intended). // Flag this thread so that when it ends, the thread beneath it will be unpaused. If that thread // (which can be the idle thread) isn't paused the following flag-change will be ignored at a later // stage. This method also relies on the fact that the current thread cannot itself be paused right // now because it is what got us here. PauseUnderlyingThread(false); // Necessary even for the "idle thread" (otherwise, the Pause command wouldn't be able to unpause it). return OK; case NEUTRAL: // the user omitted the parameter entirely, which is considered the same as "toggle" case TOGGLE: // Update for v1.0.37.06: "Pause" and "Pause Toggle" are more useful if they always apply to the // thread immediately beneath the current thread rather than "any underlying thread that's paused". if (g > g_array && g[-1].IsPaused) // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is called by the AutoExec section or a threadless callback running in thread #0. { PauseUnderlyingThread(false); return OK; } //ELSE since the underlying thread is not paused, continue onward to do the "pause enabled" logic below. // (This is the historical behavior because it allows a hotkey like F1::Pause to toggle the script's // pause state on and off -- even though what's really happening involves multiple threads.) break; default: // TOGGLE_INVALID or some other disallowed value. // We know it's a variable because otherwise the loading validation would have caught it earlier: return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); } // Since above didn't return, pause should be turned on. if (aAlwaysOperateOnUnderlyingThread) // v1.0.37.06: Allow underlying thread to be directly paused rather than pausing the current thread. { PauseUnderlyingThread(true); // If the underlying thread is already paused, this flag change will be ignored at a later stage. return OK; } // Otherwise, pause the current subroutine (which by definition isn't paused since it had to be // active to call us). It seems best not to attempt to change the Hotkey mRunAgainAfterFinished // attribute for the current hotkey (assuming it's even a hotkey that got us here) or // for them all. This is because it's conceivable that this Pause command occurred // in a background thread, such as a timed subroutine, in which case we wouldn't want the // pausing of that thread to affect anything else the user might be doing with hotkeys. // UPDATE: The above is flawed because by definition the script's quasi-thread that got // us here is now active. Since it is active, the script will immediately become dormant // when this is executed, waiting for the user to press a hotkey to launch a new // quasi-thread. Thus, it seems best to reset all the mRunAgainAfterFinished flags // in case we are in a hotkey subroutine and in case this hotkey has a buffered repeat-again // action pending, which the user probably wouldn't want to happen after the script is unpaused: #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif return OK; } ResultType Line::ScriptBlockInput(bool aEnable) // Always returns OK for caller convenience. { // Must be running Win98/2000+ for this function to be successful. // We must dynamically load the function to retain compatibility with Win95 (program won't launch // at all otherwise). typedef void (CALLBACK *BlockInput)(BOOL); static BlockInput lpfnDLLProc = (BlockInput)GetProcAddress(GetModuleHandle(_T("user32")), "BlockInput"); // Always turn input ON/OFF even if g_BlockInput says its already in the right state. This is because // BlockInput can be externally and undetectably disabled, e.g. if the user presses Ctrl-Alt-Del: if (lpfnDLLProc) (*lpfnDLLProc)(aEnable ? TRUE : FALSE); g_BlockInput = aEnable; return OK; // By design, it never returns FAIL. } Line *Line::PreparseError(LPTSTR aErrorText, LPTSTR aExtraInfo) // Returns a different type of result for use with the Pre-parsing methods. { // Make all preparsing errors critical because the runtime reliability // of the program relies upon the fact that the aren't any kind of // problems in the script (otherwise, unexpected behavior may result). // Update: It's okay to return FAIL in this case. CRITICAL_ERROR should // be avoided whenever OK and FAIL are sufficient by themselves, because // otherwise, callers can't use the NOT operator to detect if a function // failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero): LineError(aErrorText, FAIL, aExtraInfo); return NULL; // Always return NULL because the callers use it as their return value. } IObject *Line::CreateRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { // Build the parameters for Object::Create() ExprTokenType aParams[5*2]; int aParamCount = 4*2; ExprTokenType* aParam[5*2] = { aParams + 0, aParams + 1, aParams + 2, aParams + 3, aParams + 4 , aParams + 5, aParams + 6, aParams + 7, aParams + 8, aParams + 9 }; aParams[0].symbol = SYM_STRING; aParams[0].marker = _T("What"); aParams[1].symbol = SYM_STRING; aParams[1].marker = aWhat ? (LPTSTR)aWhat : g_act[mActionType].Name; aParams[2].symbol = SYM_STRING; aParams[2].marker = _T("File"); aParams[3].symbol = SYM_STRING; aParams[3].marker = Line::sSourceFile[mFileIndex]; aParams[4].symbol = SYM_STRING; aParams[4].marker = _T("Line"); aParams[5].symbol = SYM_INTEGER; aParams[5].value_int64 = mLineNumber; aParams[6].symbol = SYM_STRING; aParams[6].marker = _T("Message"); aParams[7].symbol = SYM_STRING; aParams[7].marker = (LPTSTR)aErrorText; if (aExtraInfo && *aExtraInfo) { aParamCount += 2; aParams[8].symbol = SYM_STRING; aParams[8].marker = _T("Extra"); aParams[9].symbol = SYM_STRING; aParams[9].marker = (LPTSTR)aExtraInfo; } return Object::Create(aParam, aParamCount); } ResultType Line::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { // ThrownToken may already exist if Assign() fails in ACT_CATCH, or possibly // in other extreme cases. In such a case, just free the old token. If this // line is CATCH, it won't handle the new exception; an outer TRY/CATCH will. if (g->ThrownToken) g_script.FreeExceptionToken(g->ThrownToken); ExprTokenType *token; if ( !(token = new ExprTokenType) || !(token->object = CreateRuntimeException(aErrorText, aWhat, aExtraInfo)) ) { // Out of memory. It's likely that we were called for this very reason. // Since we don't even have enough memory to allocate an exception object, // just show an error message and exit the thread. Don't call LineError(), // since that would recurse into this function. if (token) delete token; - MsgBox(ERR_OUTOFMEM ERR_ABORT); + // MsgBox(ERR_OUTOFMEM ERR_ABORT); + _fputts(ERR_OUTOFMEM ERR_ABORT, stdout) ; + return FAIL; } token->symbol = SYM_OBJECT; token->mem_to_free = NULL; g->ThrownToken = token; g->ExcptLine = this; // Returning FAIL causes each caller to also return FAIL, until either the // thread has fully exited or the recursion layer handling ACT_TRY is reached: return FAIL; } ResultType Script::ThrowRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { return g_script.mCurrLine->ThrowRuntimeException(aErrorText, aWhat, aExtraInfo); } ResultType Line::SetErrorLevelOrThrowBool(bool aError) { if (!aError) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (!g->InTryBlock) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(ERRORLEVEL_ERROR); } ResultType Line::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue) { if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(aErrorValue); } ResultType Line::SetErrorLevelOrThrowInt(int aErrorValue) { if (!aErrorValue || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); TCHAR buf[12]; // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(_itot(aErrorValue, buf, 10)); } // Logic from the above functions is duplicated in the below functions rather than calling // g_script.mCurrLine->SetErrorLevelOrThrow() to squeeze out a little extra performance for // "success" cases. These are done as overloads vs making aMessage optional to reduce code // size, since they're called from numerous places. (Even omitted parameters are passed // "explicitly" in the compiled code.) ResultType Script::SetErrorLevelOrThrowBool(bool aError) { if (!aError) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (!g->InTryBlock) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(ERRORLEVEL_ERROR); } ResultType Script::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue) { if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(ERRORLEVEL_ERROR); } ResultType Script::SetErrorLevelOrThrowStr(LPCTSTR aErrorValue, LPCTSTR aWhat) { if ((*aErrorValue == '0' && !aErrorValue[1]) || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(aErrorValue, aWhat); } ResultType Script::SetErrorLevelOrThrowInt(int aErrorValue, LPCTSTR aWhat) { if (!aErrorValue || !g->InTryBlock) return g_ErrorLevel->Assign(aErrorValue); TCHAR buf[12]; // Otherwise, an error occurred and there is a try block, so throw an exception: return ThrowRuntimeException(_itot(aErrorValue, buf, 10), aWhat); } ResultType Line::SetErrorsOrThrow(bool aError, DWORD aLastErrorOverride) { // LastError is set even if we're going to throw an exception, for simplicity: g->LastError = aLastErrorOverride == -1 ? GetLastError() : aLastErrorOverride; return SetErrorLevelOrThrowBool(aError); } #define ERR_PRINT(fmt, ...) _ftprintf(stderr, fmt, __VA_ARGS__) ResultType Line::LineError(LPCTSTR aErrorText, ResultType aErrorType, LPCTSTR aExtraInfo) { if (!aErrorText) aErrorText = _T(""); if (!aExtraInfo) aExtraInfo = _T(""); if (g->InTryBlock && (aErrorType == FAIL || aErrorType == EARLY_EXIT)) // FAIL is most common, but EARLY_EXIT is used by ComError(). WARN and CRITICAL_ERROR are excluded. return ThrowRuntimeException(aErrorText, NULL, aExtraInfo); if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute && aErrorType != WARN) // i.e. runtime errors are always displayed via dialog. { // JdeB said: // Just tested it in Textpad, Crimson and Scite. they all recognise the output and jump // to the Line containing the error when you double click the error line in the output // window (like it works in C++). Had to change the format of the line to: // printf("%s (%d) : ==> %s: \n%s \n%s\n",szInclude, nAutScriptLine, szText, szScriptLine, szOutput2 ); // MY: Full filename is required, even if it's the main file, because some editors (EditPlus) // seem to rely on that to determine which file and line number to jump to when the user double-clicks // the error message in the output window. // v1.0.47: Added a space before the colon as originally intended. Toralf said, "With this minor // change the error lexer of Scite recognizes this line as a Microsoft error message and it can be // used to jump to that line." #define STD_ERROR_FORMAT _T("%s (%d) : ==> %s\n") ERR_PRINT(STD_ERROR_FORMAT, sSourceFile[mFileIndex], mLineNumber, aErrorText); // printf() does not significantly increase the size of the EXE, probably because it shares most of the same code with sprintf(), etc. if (*aExtraInfo) ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo); } else { TCHAR buf[MSGBOX_TEXT_SIZE]; FormatError(buf, _countof(buf), aErrorType, aErrorText, aExtraInfo, this // The last parameter determines the final line of the message: , (aErrorType == FAIL && g_script.mIsReadyToExecute) ? ERR_ABORT_NO_SPACES : (aErrorType == CRITICAL_ERROR || aErrorType == FAIL) ? (g_script.mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT) : (aErrorType == EARLY_EXIT) ? _T("Continue running the script?") : NULL); g_script.mCurrLine = this; // This needs to be set in some cases where the caller didn't. #ifdef CONFIG_DEBUGGER if (g_Debugger.HasStdErrHook()) g_Debugger.OutputDebug(buf); else #endif if (MsgBox(buf, aErrorType == EARLY_EXIT ? MB_YESNO : 0) == IDNO) aErrorType = CRITICAL_ERROR; } if (aErrorType == CRITICAL_ERROR && g_script.mIsReadyToExecute) // Also ask the main message loop function to quit and announce to the system that // we expect it to quit. In most cases, this is unnecessary because all functions // called to get to this point will take note of the CRITICAL_ERROR and thus keep // return immediately, all the way back to main. However, there may cases // when this isn't true: // Note: Must do this only after MsgBox, since it appears that new dialogs can't // be created once it's done. Update: Using ExitApp() now, since it's known to be // more reliable: //PostQuitMessage(CRITICAL_ERROR); // This will attempt to run the OnExit subroutine, which should be okay since that subroutine // will terminate the script if it encounters another runtime error: g_script.ExitApp(EXIT_ERROR); return aErrorType; // The caller told us whether it should be a critical error or not. } int Line::FormatError(LPTSTR aBuf, int aBufSize, ResultType aErrorType, LPCTSTR aErrorText, LPCTSTR aExtraInfo, Line *aLine, LPCTSTR aFooter) { TCHAR source_file[MAX_PATH * 2]; if (aLine && aLine->mFileIndex) sntprintf(source_file, _countof(source_file), _T(" in #include file \"%s\""), sSourceFile[aLine->mFileIndex]); else *source_file = '\0'; // Don't bother cluttering the display if it's the main script file. LPTSTR aBuf_orig = aBuf; // Error message: aBuf += sntprintf(aBuf, aBufSize, _T("%s%s:%s %-1.500s\n\n") // Keep it to a sane size in case it's huge. , aErrorType == WARN ? _T("Warning") : (aErrorType == CRITICAL_ERROR ? _T("Critical Error") : _T("Error")) , source_file, *source_file ? _T("\n ") : _T(" "), aErrorText); // Specifically: if (*aExtraInfo) // Use format specifier to make sure really huge strings that get passed our // way, such as a var containing clipboard text, are kept to a reasonable size: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Specifically: %-1.100s%s\n\n") , aExtraInfo, _tcslen(aExtraInfo) > 100 ? _T("...") : _T("")); // Relevant lines of code: if (aLine) aBuf = aLine->VicinityToText(aBuf, BUF_SPACE_REMAINING); // What now?: if (aFooter) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\n%s"), aFooter); return (int)(aBuf - aBuf_orig); } ResultType Script::ScriptError(LPCTSTR aErrorText, LPCTSTR aExtraInfo) //, ResultType aErrorType) // Even though this is a Script method, including it here since it shares // a common theme with the other error-displaying functions: { if (mCurrLine) // If a line is available, do LineError instead since it's more specific. // If an error occurs before the script is ready to run, assume it's always critical // in the sense that the program will exit rather than run the script. // Update: It's okay to return FAIL in this case. CRITICAL_ERROR should // be avoided whenever OK and FAIL are sufficient by themselves, because // otherwise, callers can't use the NOT operator to detect if a function // failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero): return mCurrLine->LineError(aErrorText, FAIL, aExtraInfo); // Otherwise: The fact that mCurrLine is NULL means that the line currently being loaded // has not yet been successfully added to the linked list. Such errors will always result // in the program exiting. if (!aErrorText) aErrorText = _T("Unk"); // Placeholder since it shouldn't be NULL. if (!aExtraInfo) // In case the caller explicitly called it with NULL. aExtraInfo = _T(""); if (g_script.mErrorStdOut && !g_script.mIsReadyToExecute) // i.e. runtime errors are always displayed via dialog. { // See LineError() for details. ERR_PRINT(STD_ERROR_FORMAT, Line::sSourceFile[mCurrFileIndex], mCombinedLineNumber, aErrorText); if (*aExtraInfo) ERR_PRINT(_T(" Specifically: %s\n"), aExtraInfo); } else { TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); cp += sntprintf(cp, buf_space_remaining, _T("Error at line %u"), mCombinedLineNumber); // Don't call it "critical" because it's usually a syntax error. buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (mCurrFileIndex) { cp += sntprintf(cp, buf_space_remaining, _T(" in #include file \"%s\""), Line::sSourceFile[mCurrFileIndex]); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } //else don't bother cluttering the display if it's the main script file. cp += sntprintf(cp, buf_space_remaining, _T(".\n\n")); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (*aExtraInfo) { cp += sntprintf(cp, buf_space_remaining, _T("Line Text: %-1.100s%s\nError: ") // i.e. the word "Error" is omitted as being too noisy when there's no ExtraInfo to put into the dialog. , aExtraInfo // aExtraInfo defaults to "" so this is safe. , _tcslen(aExtraInfo) > 100 ? _T("...") : _T("")); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } sntprintf(cp, buf_space_remaining, _T("%s\n\n%s"), aErrorText, mIsRestart ? OLD_STILL_IN_EFFECT : WILL_EXIT); //ShowInEditor(); #ifdef CONFIG_DEBUGGER if (g_Debugger.HasStdErrHook()) g_Debugger.OutputDebug(buf); else #endif - MsgBox(buf); + _fputts(buf, stdout); } return FAIL; // See above for why it's better to return FAIL than CRITICAL_ERROR. } ResultType Script::UnhandledException(ExprTokenType*& aToken, Line* aLine) { LPCTSTR message = _T(""), extra = _T(""); TCHAR extra_buf[MAX_NUMBER_SIZE], message_buf[MAX_NUMBER_SIZE]; if (Object *ex = dynamic_cast<Object *>(TokenToObject(*aToken))) { // For simplicity and safety, we call into the Object directly rather than via Invoke(). ExprTokenType t; if (ex->GetItem(t, _T("Message"))) message = TokenToString(t, message_buf); if (ex->GetItem(t, _T("Extra"))) extra = TokenToString(t, extra_buf); if (ex->GetItem(t, _T("Line"))) { LineNumberType line_no = (LineNumberType)TokenToInt64(t); if (ex->GetItem(t, _T("File"))) { LPCTSTR file = TokenToString(t); // Locate the line by number and file index, then display that line instead // of the caller supplied one since it's probably more relevant. int file_index; for (file_index = 0; file_index < Line::sSourceFileCount; ++file_index) if (!_tcsicmp(file, Line::sSourceFile[file_index])) break; Line *line; for (line = g_script.mFirstLine; line && (line->mLineNumber != line_no || line->mFileIndex != file_index); line = line->mNextLine); if (line) aLine = line; } } } else { // Assume it's a string or number. message = TokenToString(*aToken, message_buf); } // If message is empty or numeric, display a default message for clarity. if (!*extra && IsPureNumeric(message, TRUE, TRUE, TRUE)) { extra = message; message = _T("Unhandled exception."); } TCHAR buf[MSGBOX_TEXT_SIZE]; Line::FormatError(buf, _countof(buf), FAIL, message, extra, aLine, _T("The thread has exited.")); MsgBox(buf); FreeExceptionToken(aToken); return FAIL; } void Script::FreeExceptionToken(ExprTokenType*& aToken) { // If an object was thrown, release it. if (aToken->symbol == SYM_OBJECT) aToken->object->Release(); // If a string was thrown and memory allocated for it, free it. if (aToken->mem_to_free) free(aToken->mem_to_free); // Free the token itself. delete aToken; // Clear caller's variable. aToken = NULL; } void Script::ScriptWarning(WarnMode warnMode, LPCTSTR aWarningText, LPCTSTR aExtraInfo, Line *line) { if (warnMode == WARNMODE_OFF) return; if (!line) line = mCurrLine; int fileIndex = line ? line->mFileIndex : mCurrFileIndex; FileIndexType lineNumber = line ? line->mLineNumber : mCombinedLineNumber; TCHAR buf[MSGBOX_TEXT_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); #define STD_WARNING_FORMAT _T("%s (%d) : ==> Warning: %s\n") cp += sntprintf(cp, buf_space_remaining, STD_WARNING_FORMAT, Line::sSourceFile[fileIndex], lineNumber, aWarningText); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); if (*aExtraInfo) { cp += sntprintf(cp, buf_space_remaining, _T(" Specifically: %s\n"), aExtraInfo); buf_space_remaining = (int)(_countof(buf) - (cp - buf)); } if (warnMode == WARNMODE_STDOUT) #ifndef CONFIG_DEBUGGER _fputts(buf, stdout); else OutputDebugString(buf); #else g_Debugger.FileAppendStdOut(buf); else g_Debugger.OutputDebug(buf); #endif // In MsgBox mode, MsgBox is in addition to OutputDebug if (warnMode == WARNMODE_MSGBOX) { if (!line) line = mCurrLine; // Call mCurrLine->LineError() vs ScriptError() to pass WARN. if (line) line->LineError(aWarningText, WARN, aExtraInfo); else // Realistically shouldn't happen. If it does, the message might be slightly // misleading since ScriptError isn't equipped to display "warning" messages. ScriptError(aWarningText, aExtraInfo); } } void Script::WarnUninitializedVar(Var *var) { bool isGlobal = !var->IsLocal(); WarnMode warnMode = isGlobal ? g_Warn_UseUnsetGlobal : g_Warn_UseUnsetLocal; if (!warnMode) return; // Note: If warning mode is MsgBox, this method has side effect of marking the var initialized, so that // only a single message box gets raised per variable. (In other modes, e.g. OutputDebug, the var remains // uninitialized because it may be beneficial to see the quantity and various locations of uninitialized // uses, and doesn't present the same user interface problem that multiple message boxes can.) if (warnMode == WARNMODE_MSGBOX) var->MarkInitialized(); bool isNonStaticLocal = var->IsNonStaticLocal(); LPCTSTR varClass = isNonStaticLocal ? _T("local") : (isGlobal ? _T("global") : _T("static")); LPCTSTR sameNameAsGlobal = (isNonStaticLocal && FindVar(var->mName, 0, NULL, FINDVAR_GLOBAL)) ? _T(" with same name as a global") : _T(""); TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); sntprintf(cp, buf_space_remaining, _T("%s (a %s variable%s)"), var->mName, varClass, sameNameAsGlobal); ScriptWarning(warnMode, WARNING_USE_UNSET_VARIABLE, buf); } void Script::MaybeWarnLocalSameAsGlobal(Func &func, Var &var) // Caller has verified the following: // 1) var is not a declared variable. // 2) a global variable with the same name definitely exists. { if (!g_Warn_LocalSameAsGlobal) return; #ifdef ENABLE_DLLCALL if (IsDllArgTypeName(var.mName)) // Exclude unquoted DllCall arg type names. Although variable names like "str" and "ptr" // might be used for other purposes, it seems far more likely that both this var and its // global counterpart (if it exists) are blank vars which were used as DllCall arg types. return; #endif Line *line = func.mJumpToLine; while (line && line->mActionType != ACT_BLOCK_BEGIN) line = line->mPrevLine; if (!line) line = func.mJumpToLine; TCHAR buf[DIALOG_TITLE_SIZE], *cp = buf; int buf_space_remaining = (int)_countof(buf); sntprintf(cp, buf_space_remaining, _T("%s (in function %s)"), var.mName, func.mName); ScriptWarning(g_Warn_LocalSameAsGlobal, WARNING_LOCAL_SAME_AS_GLOBAL, buf, line); } void Script::PreprocessLocalVars(Func &aFunc, Var **aVarList, int &aVarCount) { for (int v = 0; v < aVarCount; ++v) { Var &var = *aVarList[v]; if (var.IsDeclared()) // Not a canditate for a super-global or warning. continue; Var *global_var = FindVar(var.mName, 0, NULL, FINDVAR_GLOBAL); if (!global_var) // No global variable with that name. continue; if (global_var->IsSuperGlobal()) { // Make this local variable an alias for the super-global. Above has already // verified this var was not declared and therefore isn't a function parameter. var.UpdateAlias(global_var); // Remove the variable from the local list to prevent it from being shown in // ListVars or being reset when the function returns. memmove(aVarList + v, aVarList + v + 1, (--aVarCount - v) * sizeof(Var *)); --v; // Counter the loop's increment. } else // Since this undeclared local variable has the same name as a global, there's // a chance the user intended it to be global. So consider warning the user: MaybeWarnLocalSameAsGlobal(aFunc, var); } } #ifndef MINIDLL LPTSTR Script::ListVars(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates this script's list of variables into text equivalent, putting the result // into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; Func *current_func = g->CurrentFunc ? g->CurrentFunc : g->CurrentFuncGosub; if (current_func) { // This definition might help compiler string pooling by ensuring it stays the same for both usages: #define LIST_VARS_UNDERLINE _T("\r\n--------------------------------------------------\r\n") // Start at the oldest and continue up through the newest: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("Local Variables for %s()%s"), current_func->mName, LIST_VARS_UNDERLINE); Func &func = *current_func; // For performance. for (int i = 0; i < func.mVarCount; ++i) if (func.mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars. aBuf = func.mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true); } // v1.0.31: The description "alphabetical" is kept even though it isn't quite true // when the lazy variable list exists, since those haven't yet been sorted into the main list. // However, 99.9% of scripts do not use the lazy list, so it seems too rare to worry about other // than document it in the ListVars command in the help file: aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%sGlobal Variables (alphabetical)%s") , current_func ? _T("\r\n\r\n") : _T(""), LIST_VARS_UNDERLINE); // Start at the oldest and continue up through the newest: for (int i = 0; i < mVarCount; ++i) if (mVar[i]->Type() == VAR_NORMAL) // Don't bother showing clipboard and other built-in vars. aBuf = mVar[i]->ToText(aBuf, BUF_SPACE_REMAINING, true); return aBuf; } LPTSTR Script::ListKeyHistory(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates this key history into text equivalent, putting the result // into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; // Needed for the BUF_SPACE_REMAINING macro. // I was initially concerned that GetWindowText() can hang if the target window is // hung. But at least on newer OS's, this doesn't seem to be a problem: MSDN says // "If the window does not have a caption, the return value is a null string. This // behavior is by design. It allows applications to call GetWindowText without hanging // if the process that owns the target window is hung. However, if the target window // is hung and it belongs to the calling application, GetWindowText will hang the // calling application." HWND target_window = GetForegroundWindow(); TCHAR win_title[100]; if (target_window) GetWindowText(target_window, win_title, _countof(win_title)); else *win_title = '\0'; TCHAR timer_list[128] = _T(""); for (ScriptTimer *timer = mFirstTimer; timer != NULL; timer = timer->mNextTimer) if (timer->mEnabled) sntprintfcat(timer_list, _countof(timer_list) - 3, _T("%s "), timer->mLabel->mName); // Allow room for "..." if (*timer_list) { size_t length = _tcslen(timer_list); if (length > (_countof(timer_list) - 5)) tcslcpy(timer_list + length, _T("..."), _countof(timer_list) - length); else if (timer_list[length - 1] == ' ') timer_list[--length] = '\0'; // Remove the last space if there was room enough for it to have been added. } TCHAR LRtext[256]; aBuf += sntprintf(aBuf, aBufSize, _T("Window: %s") //"\r\nBlocks: %u" _T("\r\nKeybd hook: %s") _T("\r\nMouse hook: %s") _T("\r\nEnabled Timers: %u of %u (%s)") //"\r\nInterruptible?: %s" _T("\r\nInterrupted threads: %d%s") _T("\r\nPaused threads: %d of %d (%d layers)") _T("\r\nModifiers (GetKeyState() now) = %s") _T("\r\n") , win_title //, SimpleHeap::GetBlockCount() , g_KeybdHook == NULL ? _T("no") : _T("yes") , g_MouseHook == NULL ? _T("no") : _T("yes") , mTimerEnabledCount, mTimerCount, timer_list //, INTERRUPTIBLE ? "yes" : "no" , g_nThreads > 1 ? g_nThreads - 1 : 0 , g_nThreads > 1 ? _T(" (preempted: they will resume when the current thread finishes)") : _T("") , g_nPausedThreads - (g_array[0].IsPaused && !mAutoExecSectionIsRunning) // Historically thread #0 isn't counted as a paused thread unless the auto-exec section is running but paused. , g_nThreads, g_nLayersNeedingTimer , ModifiersLRToText(GetModifierLRState(true), LRtext)); GetHookStatus(aBuf, BUF_SPACE_REMAINING); aBuf += _tcslen(aBuf); // Adjust for what GetHookStatus() wrote to the buffer. return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, g_KeyHistory ? _T("\r\nPress [F5] to refresh.") : _T("\r\nKey History has been disabled via #KeyHistory 0.")); } #endif ResultType Script::ActionExec(LPTSTR aAction, LPTSTR aParams, LPTSTR aWorkingDir, bool aDisplayErrors , LPTSTR aRunShowMode, HANDLE *aProcess, bool aUpdateLastError, bool aUseRunAs, Var *aOutputVar) // Caller should specify NULL for aParams if it wants us to attempt to parse out params from // within aAction. Caller may specify empty string ("") instead to specify no params at all. // Remember that aAction and aParams can both be NULL, so don't dereference without checking first. // Note: For the Run & RunWait commands, aParams should always be NULL. Params are parsed out of // the aActionString at runtime, here, rather than at load-time because Run & RunWait might contain // dereferenced variable(s), which can only be resolved at runtime. { HANDLE hprocess_local; HANDLE &hprocess = aProcess ? *aProcess : hprocess_local; // To simplify other things. hprocess = NULL; // Init output param if the caller gave us memory to store it. Even if caller didn't, other things below may rely on this being initialized. if (aOutputVar) // Same aOutputVar->Assign(); // Launching nothing is always a success: if (!aAction || !*aAction) return OK; // Make sure this is set to NULL because CreateProcess() won't work if it's the empty string: if (aWorkingDir && !*aWorkingDir) aWorkingDir = NULL; #define IS_VERB(str) ( !_tcsicmp(str, _T("find")) || !_tcsicmp(str, _T("explore")) || !_tcsicmp(str, _T("open"))\ || !_tcsicmp(str, _T("edit")) || !_tcsicmp(str, _T("print")) || !_tcsicmp(str, _T("properties")) ) // Set default items to be run by ShellExecute(). These are also used by the error // reporting at the end, which is why they're initialized even if CreateProcess() works // and there's no need to use ShellExecute(): LPTSTR shell_verb = NULL; LPTSTR shell_action = aAction; LPTSTR shell_params = NULL; /////////////////////////////////////////////////////////////////////////////////// // This next section is done prior to CreateProcess() because when aParams is NULL, // we need to find out whether aAction contains a system verb. /////////////////////////////////////////////////////////////////////////////////// if (aParams) // Caller specified the params (even an empty string counts, for this purpose). { if (IS_VERB(shell_action)) { shell_verb = shell_action; shell_action = aParams; } else shell_params = aParams; } else // Caller wants us to try to parse params out of aAction. { // Find out the "first phrase" in the string to support the special "find" and "explore" operations. LPTSTR phrase; size_t phrase_len; // Set phrase_end to be the location of the first whitespace char, if one exists: LPTSTR phrase_end = StrChrAny(shell_action, _T(" \t")); // Find space or tab. if (phrase_end) // i.e. there is a second phrase. { phrase_len = phrase_end - shell_action; // Create a null-terminated copy of the phrase for comparison. phrase = tmemcpy(talloca(phrase_len + 1), shell_action, phrase_len); phrase[phrase_len] = '\0'; // Firstly, treat anything following '*' as a verb, to support custom verbs like *Compile. if (*phrase == '*') shell_verb = phrase + 1; // Secondly, check for common system verbs like "find" and "edit". else if (IS_VERB(phrase)) shell_verb = phrase; if (shell_verb) // Exclude the verb and its trailing space or tab from further consideration. shell_action += phrase_len + 1; // Otherwise it's not a verb, and may be re-parsed later. } // shell_action will be split into action and params at a later stage if ShellExecuteEx is to be used. } // This is distinct from hprocess being non-NULL because the two aren't always the // same. For example, if the user does "Run, find D:\" or "RunWait, www.yahoo.com", // no new process handle will be available even though the launch was successful: bool success = false; TCHAR system_error_text[512] = _T(""); bool use_runas = aUseRunAs && (!mRunAsUser.IsEmpty() || !mRunAsPass.IsEmpty() || !mRunAsDomain.IsEmpty()); if (use_runas && shell_verb) { if (aDisplayErrors) ScriptError(_T("System verbs unsupported with RunAs.")); return FAIL; } size_t action_length = _tcslen(shell_action); // shell_action == aAction if shell_verb == NULL. if (action_length >= LINE_SIZE) // Max length supported by CreateProcess() is 32 KB. But there hasn't been any demand to go above 16 KB, so seems little need to support it (plus it reduces risk of stack overflow). { if (aDisplayErrors) ScriptError(_T("String too long.")); // Short msg since so rare. return FAIL; } // If the caller originally gave us NULL for aParams, always try CreateProcess() before // trying ShellExecute(). This is because ShellExecute() is usually a lot slower. // The only exception is if the action appears to be a verb such as open, edit, or find. // In that case, we'll also skip the CreateProcess() attempt and do only the ShellExecute(). // If the user really meant to launch find.bat or find.exe, for example, he should add // the extension (e.g. .exe) to differentiate "find" from "find.exe": if (!shell_verb) { STARTUPINFO si = {0}; // Zero fill to be safer. si.cb = sizeof(si); // The following are left at the default of NULL/0 set higher above: //si.lpReserved = si.lpDesktop = si.lpTitle = NULL; //si.lpReserved2 = NULL; si.dwFlags = STARTF_USESHOWWINDOW; // This tells it to use the value of wShowWindow below. si.wShowWindow = (aRunShowMode && *aRunShowMode) ? Line::ConvertRunMode(aRunShowMode) : SW_SHOWNORMAL; PROCESS_INFORMATION pi = {0}; // Since CreateProcess() requires that the 2nd param be modifiable, ensure that it is // (even if this is ANSI and not Unicode; it's just safer): LPTSTR command_line; if (aParams && *aParams) { command_line = talloca(action_length + _tcslen(aParams) + 10); // +10 to allow room for space, terminator, and any extra chars that might get added in the future. _stprintf(command_line, _T("%s %s"), aAction, aParams); } else // We're running the original action from caller. { command_line = talloca(action_length + 1); _tcscpy(command_line, aAction); // CreateProcessW() requires modifiable string. Although non-W version is used now, it feels safer to make it modifiable anyway. } if (use_runas) { if (!DoRunAs(command_line, aWorkingDir, aDisplayErrors, aUpdateLastError, si.wShowWindow // wShowWindow (min/max/hide). , aOutputVar, pi, success, hprocess, system_error_text)) // These are output parameters it will set for us. return FAIL; // It already displayed the error, if appropriate. } else { // MSDN: "If [lpCurrentDirectory] is NULL, the new process is created with the same // current drive and directory as the calling process." (i.e. since caller may have // specified a NULL aWorkingDir). Also, we pass NULL in for the first param so that // it will behave the following way (hopefully under all OSes): "the first white-space delimited // token of the command line specifies the module name. If you are using a long file name that // contains a space, use quoted strings to indicate where the file name ends and the arguments // begin (see the explanation for the lpApplicationName parameter). If the file name does not // contain an extension, .exe is appended. Therefore, if the file name extension is .com, // this parameter must include the .com extension. If the file name ends in a period (.) with // no extension, or if the file name contains a path, .exe is not appended. If the file name does // not contain a directory path, the system searches for the executable file in the following // sequence...". // Provide the app name (first param) if possible, for greater expected reliability. // UPDATE: Don't provide the module name because if it's enclosed in double quotes, // CreateProcess() will fail, at least under XP: //if (CreateProcess(aParams && *aParams ? aAction : NULL if (CreateProcess(NULL, command_line, NULL, NULL, FALSE, 0, NULL, aWorkingDir, &si, &pi)) { success = true; if (pi.hThread) CloseHandle(pi.hThread); // Required to avoid memory leak. hprocess = pi.hProcess; if (aOutputVar) aOutputVar->Assign(pi.dwProcessId); } else GetLastErrorText(system_error_text, _countof(system_error_text), aUpdateLastError); } } if (!success) // Either the above wasn't attempted, or the attempt failed. So try ShellExecute(). { if (use_runas) { // Since CreateProcessWithLogonW() was either not attempted or did not work, it's probably // best to display an error rather than trying to run it without the RunAs settings. // This policy encourages users to have RunAs in effect only when necessary: if (aDisplayErrors) ScriptError(_T("Launch Error (possibly related to RunAs)."), system_error_text); return FAIL; } SHELLEXECUTEINFO sei = {0}; // sei.hwnd is left NULL to avoid potential side-effects with having a hidden window be the parent. // However, doing so may result in the launched app appearing on a different monitor than the // script's main window appears on (for multimonitor systems). This seems fairly inconsequential // since scripted workarounds are possible. sei.cbSize = sizeof(sei); // Below: "indicate that the hProcess member receives the process handle" and not to display error dialog: sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; sei.lpDirectory = aWorkingDir; // OK if NULL or blank; that will cause current dir to be used. sei.nShow = (aRunShowMode && *aRunShowMode) ? Line::ConvertRunMode(aRunShowMode) : SW_SHOWNORMAL; if (shell_verb) { sei.lpVerb = shell_verb; if (!_tcsicmp(shell_verb, _T("properties"))) sei.fMask |= SEE_MASK_INVOKEIDLIST; // Need to use this for the "properties" verb to work reliably. } if (!shell_params) // i.e. above hasn't determined the params yet. { // Rather than just consider the first phrase to be the executable and the rest to be the param, we check it // for a proper extension so that the user can launch a document name containing spaces, without having to // enclose it in double quotes. UPDATE: Want to be able to support executable filespecs without requiring them // to be enclosed in double quotes. Therefore, search the entire string, rather than just first_phrase, for // the left-most occurrence of a valid executable extension. This should be fine since the user can still // pass in EXEs and such as params as long as the first executable is fully qualified with its real extension // so that we can tell that it's the action and not one of the params. UPDATE: Since any file type may // potentially accept parameters (.lnk or .ahk files for instance), the first space-terminated substring which // is either an existing file or ends in one of .exe,.bat,.com,.cmd,.hta is considered the executable and the
tinku99/ahkdll
d467ddf473042e98a0dc41325e31d91ff7ca173f
removed commands
diff --git a/.gitignore b/.gitignore index 2055323..3a8bb4d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ AutoHotkey.sdf +*.opensdf AutoHotkey.suo AutoHotkey.vcxproj.user ComServer_h.h ComServer_i.c Test bin ipch temp
tinku99/ahkdll
18fe8d99badd67a34d9c7db3fc93f1a62e75468a
removed commands
diff --git a/source/script.cpp b/source/script.cpp index 0826fe1..badd978 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -15608,2023 +15608,2028 @@ ResultType Line::PerformLoopParseCSV(ExprTokenType *aResultToken, bool &aContinu ResultType Line::PerformLoopReadFile(ExprTokenType *aResultToken, bool &aContinueMainLoop, Line *&aJumpToLine, Line *aUntil , TextStream *aReadFile, LPTSTR aWriteFileName) { LoopReadFileStruct loop_info(aReadFile, aWriteFileName); size_t line_length; ResultType result; Line *jump_to_line; global_struct &g = *::g; // Primarily for performance in this case. for (;; ++g.mLoopIteration) { if ( !(line_length = loop_info.mReadFile->ReadLine(loop_info.mCurrentLine, _countof(loop_info.mCurrentLine) - 1)) ) // -1 to ensure there's room for a null-terminator. { // We want to return OK except in some specific cases handled below (see "break"). result = OK; break; } if (loop_info.mCurrentLine[line_length - 1] == '\n') // Remove newlines like FileReadLine does. --line_length; loop_info.mCurrentLine[line_length] = '\0'; g.mLoopReadFile = &loop_info; if (mNextLine->mActionType == ACT_BLOCK_BEGIN) // See PerformLoop() for comments about this section. do result = mNextLine->mNextLine->ExecUntil(UNTIL_BLOCK_END, aResultToken, &jump_to_line); while (jump_to_line == mNextLine); else result = mNextLine->ExecUntil(ONLY_ONE_LINE, aResultToken, &jump_to_line); if (jump_to_line && !(result == LOOP_CONTINUE && jump_to_line == this)) // See comments in PerformLoop() about this section. { if (jump_to_line == this) aContinueMainLoop = true; else aJumpToLine = jump_to_line; // Signal our caller to handle this jump. break; } if (result != OK && result != LOOP_CONTINUE) // i.e. result == LOOP_BREAK || result == EARLY_RETURN || result == EARLY_EXIT || result == FAIL) break; if (aUntil && aUntil->EvaluateLoopUntil(result)) break; } if (loop_info.mWriteFile) { loop_info.mWriteFile->Close(); delete loop_info.mWriteFile; } return result; } __forceinline ResultType Line::Perform() // As of 2/9/2009, __forceinline() reduces code size a little (since this function is called from only one place) and boosts performance a bit, though it's probably more due to the butterfly effect and cache hits/misses. // Performs only this line's action. // Returns OK or FAIL. // The function should not be called to perform any flow-control actions such as // Goto, Gosub, Return, Block-Begin, Block-End, If, Else, etc. { TCHAR buf_temp[MAX_REG_ITEM_SIZE], *contents; // For registry and other things. WinGroup *group; // For the group commands. Var *arg_var2, *output_var = OUTPUT_VAR; // Okay if NULL. Users of it should only consider it valid if their first arg is actually an output_variable. global_struct &g = *::g; // Reduces code size due to replacing so many g-> with g. Eclipsing ::g with local g makes compiler remind/enforce the use of the right one. BOOL arg2_has_binary_integer; ToggleValueType toggle; // For commands that use on/off/neutral. // Use signed values for these in case they're really given an explicit negative value: int start_char_num, chars_to_extract; // For String commands. size_t source_length; // For String commands. SymbolType var_is_pure_numeric, value_is_pure_numeric; // For math operations. vk_type vk; // For GetKeyState. Label *target_label; // For ACT_SETTIMER and ACT_HOTKEY int instance_number; // For sound commands. DWORD component_type; // For sound commands. __int64 device_id; // For sound commands. __int64 helps avoid compiler warning for some conversions. bool is_remote_registry; // For Registry commands. HKEY root_key; // For Registry commands. ResultType result; // General purpose. // Even though the loading-parser already checked, check again, for now, // at least until testing raises confidence. UPDATE: Don't this because // sometimes (e.g. ACT_ASSIGN/ADD/SUB/MULT/DIV) the number of parameters // required at load-time is different from that at runtime, because params // are taken out or added to the param list: //if (nArgs < g_act[mActionType].MinParams) ... switch (mActionType) { case ACT_ASSIGN: // Note: This line's args have not yet been dereferenced in this case (i.e. ExpandArgs() hasn't been // called). The below function will handle that if it is needed. return PerformAssign(); // It will report any errors for us. case ACT_ASSIGNEXPR: // Currently, ACT_ASSIGNEXPR can occur even when mArg[1].is_expression==false, such as things like var:=5 // and var:=Array%i%. Search on "is_expression = " to find such cases in the script-loading/parsing // routines. if (mArgc > 1) { if (mArg[1].is_expression) // v1.0.45: ExpandExpression() already took care of it for us (for performance reasons). return OK; // Above must be checked prior to below since each uses "postfix" in a different way. if (mArg[1].postfix) // There is a cached binary integer. return output_var->Assign(*(__int64 *)mArg[1].postfix); // sArgVar is used to enhance performance, which would otherwise be poor for dynamic variables // such as Var:=Array%i% (which is an expression and handled by ACT_ASSIGNEXPR rather than // ACT_ASSIGN) because Array%i% would have to be resolved twice (once here and once // previously by ExpandArgs()) just to find out if it's IsBinaryClip()). // If ARG2 isn't blank, this ACT_ASSIGNEXPR is assigning an environment variable or g_ErrorLevel // (e.g. var:=Username); so can't apply this optimization. if (ARGVARRAW2 && !*ARG2) // See above. Also, RAW is safe due to the above check of mArgc > 1. { switch(ARGVARRAW2->Type()) { case VAR_NORMAL: // This can be reached via things like: x:=single_naked_var_including_binary_clip // Assign var to var in case ARGVARRAW2->IsBinaryClip(), and for others because // var-to-var has optimizations like retaining the copying over the cached binary number. // In the case of ARGVARRAW2->IsBinaryClip(), performance should be good since // IsBinaryClip() implies a single isolated deref, which would never have been copied // into the deref buffer. // // v1.0.46.01: ARGVARRAW2->IsBinaryClip() can be true because loadtime no longer translates // such statements into ACT_ASSIGN vs. ACT_ASSIGNEXPR. Even without that change, it can also // be reached by something like: // DynClipboardAll = ClipboardAll // ClipSaved := %DynClipboardAll% return output_var->Assign(*ARGVARRAW2); // Var-to-var copy supports ARGVARRAW2 being binary clipboard, and also exploits caching of binary numbers, for performance. case VAR_CLIPBOARDALL: return output_var->AssignClipboardAll(); //Otherwise it's VAR_CLIPBOARD or a read-only variable; continue on to do assign the normal way. } } } // Since above didn't return: // Note that simple assignments such as Var:="xyz" or Var:=Var2 are resolved to be // non-expressions at load-time. In these cases, ARG2 would have been expanded // normally rather than evaluated as an expression. return output_var->Assign(ARG2); // ARG2 now contains the above or the evaluated result of the expression. case ACT_EXPRESSION: // Nothing needs to be done because the expression in ARG1 (which is the only arg) has already // been evaluated and its functions and subfunctions called. Examples: // fn(123, "string", var, fn2(y)) // x&=3 // var ? func() : x:=y return OK; // Like AutoIt2, if either output_var or ARG1 aren't purely numeric, they // will be considered to be zero for all of the below math functions: case ACT_ADD: // Notes about the macro below: // Ordered for short-circuit performance. No need to check if it's g_ErrorLevel (like // ArgMustBeDereferenced() does) because the commands that use it don't internally change ErrorLevel. // RAW is safe because loadtime validation ensured there are at least 2 args. // ACT_ADD/SUB/MULT/DIV are one of the few places that pass true to IsNonBlankIntegerOrFloat(true). // This is for backward compatibility. #define DEFINE_ARG_VAR2 arg_var2 = (ARGVARRAW2 && !*ARG2 && ARGVARRAW2->Type() == VAR_NORMAL) ? ARGVARRAW2 : NULL; #undef DETERMINE_NUMERIC_TYPES #define DETERMINE_NUMERIC_TYPES \ if (arg2_has_binary_integer = mArg[1].postfix && !mArg[1].is_expression)\ {\ value_is_pure_numeric = PURE_INTEGER;\ arg_var2 = NULL;\ }\ else\ {\ DEFINE_ARG_VAR2 \ value_is_pure_numeric = arg_var2 ? arg_var2->IsNonBlankIntegerOrFloat(true)\ : IsPureNumeric(ARG2, true, false, true, true);\ }\ var_is_pure_numeric = output_var->IsNonBlankIntegerOrFloat(true); #undef ARG2_AS_DOUBLE #undef ARG2_AS_INT64 #define ARG2_AS_DOUBLE (arg2_has_binary_integer ? (double)*(__int64*)mArg[1].postfix \ : arg_var2 ? arg_var2->ToDouble(FALSE) : ATOF(ARG2)) #define ARG2_AS_INT64 (arg2_has_binary_integer ? *(__int64*)mArg[1].postfix \ : (arg_var2 ? arg_var2->ToInt64(FALSE) : ATOI64(ARG2))) // Some performance can be gained by relying on the fact that short-circuit boolean // can skip the "var_is_pure_numeric" check whenever value_is_pure_numeric == PURE_FLOAT. // This is because var_is_pure_numeric is never directly needed here (unlike EvaluateCondition()). // However, benchmarks show that this makes such a small difference that it's not worth the // loss of maintainability and the slightly larger code size due to macro expansion: //#undef IF_EITHER_IS_FLOAT //#define IF_EITHER_IS_FLOAT if (value_is_pure_numeric == PURE_FLOAT \ // || IsPureNumeric(output_var->Contents(), true, false, true, true) == PURE_FLOAT) DETERMINE_NUMERIC_TYPES if (!*ARG3 || !_tcschr(_T("SMHD"), ctoupper(*ARG3))) // ARG3 is absent or invalid, so do normal math (not date-time). { IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) + ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) + ARG2_AS_INT64); } // Since above didn't return, the command is being used to add a value to a date-time. if (!value_is_pure_numeric) // It's considered to be zero, so the output_var is left unchanged: return OK; // Since above didn't return: // Use double to support a floating point value for days, hours, minutes, etc: double nUnits; // Declaring separate from initializing avoids compiler warning when not inside a block. nUnits = ARG2_AS_DOUBLE; FILETIME ft, ftNowUTC; if (*output_var->Contents()) { if (!YYYYMMDDToFileTime(output_var->Contents(), ft)) return output_var->Assign(_T("")); // Set to blank to indicate the problem. } else // The output variable is currently blank, so substitute the current time for it. { GetSystemTimeAsFileTime(&ftNowUTC); FileTimeToLocalFileTime(&ftNowUTC, &ft); // Convert UTC to local time. } // Convert to 10ths of a microsecond (the units of the FILETIME struct): switch (ctoupper(*ARG3)) { case 'S': // Seconds nUnits *= (double)10000000; break; case 'M': // Minutes nUnits *= ((double)10000000 * 60); break; case 'H': // Hours nUnits *= ((double)10000000 * 60 * 60); break; case 'D': // Days nUnits *= ((double)10000000 * 60 * 60 * 24); break; } // 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; // Add the specified amount of time to the result value: ul.QuadPart += (__int64)nUnits; // Seems ok to cast/truncate in light of the *=10000000 above. // Convert back into ft struct: ft.dwLowDateTime = ul.LowPart; ft.dwHighDateTime = ul.HighPart; return output_var->Assign(FileTimeToYYYYMMDD(buf_temp, ft, false)); case ACT_SUB: if (!*ARG3 || !_tcschr(_T("SMHD"), ctoupper(*ARG3))) // ARG3 is absent or invalid, so do normal math (not date-time). { DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) - ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) - ARG2_AS_INT64); } // Since above didn't return, the command is being used to subtract date-time values. bool failed; // If either ARG2 or output_var->Contents() is blank, it will default to the current time: __int64 time_until; // Declaring separate from initializing avoids compiler warning when not inside a block. DEFINE_ARG_VAR2 time_until = YYYYMMDDSecondsUntil(arg_var2 ? arg_var2->Contents() : ARG2 , output_var->Contents(), failed); if (failed) // Usually caused by an invalid component in the date-time string. return output_var->Assign(_T("")); switch (ctoupper(*ARG3)) { // Do nothing in the case of 'S' (seconds). Otherwise: case 'M': time_until /= 60; break; // Minutes case 'H': time_until /= 60 * 60; break; // Hours case 'D': time_until /= 60 * 60 * 24; break; // Days } // Only now that any division has been performed (to reduce the magnitude of // time_until) do we cast down into an int, which is the standard size // used for non-float results (the result is always non-float for subtraction // of two date-times): return output_var->Assign(time_until); // Assign as signed 64-bit. case ACT_MULT: DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) * ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) * ARG2_AS_INT64); case ACT_DIV: DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT { double ARG2_as_float = ARG2_AS_DOUBLE; if (!ARG2_as_float) // v1.0.46: Make behavior more consistent with expressions by return output_var->Assign(); // avoiding a runtime error dialog; just make the output variable blank. return output_var->Assign(output_var->ToDouble(FALSE) / ARG2_as_float); } else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. { __int64 ARG2_as_int = ARG2_AS_INT64; if (!ARG2_as_int) // v1.0.46: Make behavior more consistent with expressions by return output_var->Assign(); // avoiding a runtime error dialog; just make the output variable blank. return output_var->Assign(output_var->ToInt64(FALSE) / ARG2_as_int); } case ACT_STRINGLEFT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) // For these we don't report an error, since it might be intentional for // it to be called this way, in which case it will do nothing other than // set the output var to be blank. chars_to_extract = 0; else { source_length = ArgLength(2); // Should be quick because Arg2 is an InputVar (except when it's a built-in var perhaps). if (chars_to_extract > (int)source_length) chars_to_extract = (int)source_length; // Assign() requires a length that's <= the actual length of the string. } // It will display any error that occurs. return output_var->Assign(ARG2, chars_to_extract); case ACT_STRINGRIGHT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) chars_to_extract = (int)source_length; // It will display any error that occurs: return output_var->Assign(ARG2 + source_length - chars_to_extract, chars_to_extract); case ACT_STRINGMID: // v1.0.43.10: Allow chars-to-extract to be blank, which means "get all characters". // However, for backward compatibility, examine the raw arg, not ARG4. That way, any existing // scripts that use a variable reference or expression that resolves to an empty string will // have the parameter treated as zero (as in previous versions) rather than "all characters". if (mArgc < 4 || !*mArg[3].text) chars_to_extract = INT_MAX; else { chars_to_extract = ArgToInt(4); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 1) return output_var->Assign(); // Set it to be blank in this case. } start_char_num = ArgToInt(3); if (ctoupper(*ARG5) == 'L') // Chars to the left of start_char_num will be extracted. { // TRANSLATE "L" MODE INTO THE EQUIVALENT NORMAL MODE: if (start_char_num < 1) // Starting at a character number that is invalid for L mode. return output_var->Assign(); // Blank seems most appropriate for the L option in this case. start_char_num -= (chars_to_extract - 1); if (start_char_num < 1) // Reduce chars_to_extract to reflect the fact that there aren't enough chars // to the left of start_char_num, so we'll extract only them: chars_to_extract -= (1 - start_char_num); } // ABOVE HAS CONVERTED "L" MODE INTO NORMAL MODE, so "L" no longer needs to be considered below. // UPDATE: The below is also needed for the L option to work correctly. Older: // It's somewhat debatable, but it seems best not to report an error in this and // other cases. The result here is probably enough to speak for itself, for script // debugging purposes: if (start_char_num < 1) start_char_num = 1; // 1 is the position of the first char, unlike StringGetPos. source_length = ArgLength(2); // This call seems unavoidable in both "L" mode and normal mode. if (source_length < (UINT)start_char_num) // Source is empty or start_char_num lies to the right of the entire string. return output_var->Assign(); // No chars exist there, so set it to be blank. source_length -= (start_char_num - 1); // Fix for v1.0.44.14: Adjust source_length to be the length starting at start_char_num. Otherwise, the length passed to Assign() could be too long, and it now expects an accurate length. if ((UINT)chars_to_extract > source_length) chars_to_extract = (int)source_length; return output_var->Assign(ARG2 + start_char_num - 1, chars_to_extract); case ACT_STRINGTRIMLEFT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) // This could be intentional, so don't display an error. chars_to_extract = (int)source_length; return output_var->Assign(ARG2 + chars_to_extract, (VarSizeType)(source_length - chars_to_extract)); case ACT_STRINGTRIMRIGHT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) // This could be intentional, so don't display an error. chars_to_extract = (int)source_length; return output_var->Assign(ARG2, (VarSizeType)(source_length - chars_to_extract)); // It already displayed any error. case ACT_STRINGLOWER: case ACT_STRINGUPPER: contents = output_var->Contents(TRUE, TRUE); // Set default. if (contents != ARG2 || output_var->Type() != VAR_NORMAL) // It's compared this way in case ByRef/aliases are involved. This will detect even them. { // Clipboard is involved and/or source != dest. Do it the more comprehensive way. // Set up the var, enlarging it if necessary. If the output_var is of type VAR_CLIPBOARD, // this call will set up the clipboard for writing. // Fix for v1.0.45.02: The v1.0.45 change where the value is assigned directly without sizing the // variable first doesn't work in cases when the variable is the clipboard. This is because the // clipboard's buffer is changeable (for the case conversion later below) only when using the following // approach, not a simple "assign then modify its Contents()". if (output_var->AssignString(NULL, ArgLength(2)) != OK) // The length is in characters, so AssignString(NULL, ...) return FAIL; contents = output_var->Contents(); // Do this only after the above might have changed the contents mem address. // Copy the input variable's text directly into the output variable: _tcscpy(contents, ARG2); } //else input and output are the same, normal variable; so nothing needs to be copied over. Just leave // contents at the default set earlier, then convert its case. if (*ARG3 && ctoupper(*ARG3) == 'T' && !*(ARG3 + 1)) // Convert to title case. StrToTitleCase(contents); else if (mActionType == ACT_STRINGLOWER) CharLower(contents); else CharUpper(contents); return output_var->Close(); // In case it's the clipboard. case ACT_STRINGLEN: return output_var->Assign((__int64)(ARGVARRAW2 && ARGVARRAW2->IsBinaryClip() // Load-time validation has ensured mArgc > 1. ? ARGVARRAW2->Length() // Total size of the binary clip. : ArgLength(2))); // The above must be kept in sync with the StringLen() function elsewhere. case ACT_STRINGGETPOS: { LPTSTR arg4 = ARG4; int pos = -1; // Set default. int occurrence_number; if (*arg4 && _tcschr(_T("LR"), ctoupper(*arg4))) occurrence_number = *(arg4 + 1) ? ATOI(arg4 + 1) : 1; else occurrence_number = 1; // Intentionally allow occurrence_number to resolve to a negative, for scripting flexibility: if (occurrence_number > 0) { if (!*ARG3) // It might be intentional, in obscure cases, to search for the empty string. pos = 0; // Above: empty string is always found immediately (first char from left) regardless // of whether the search will be conducted from the right. This is because it's too // rare to worry about giving it any more explicit handling based on search direction. else { LPTSTR found, haystack = ARG2, needle = ARG3; int offset = ArgToInt(5); // v1.0.30.03 if (offset < 0) offset = 0; size_t haystack_length = ArgLength(2); if (offset < (int)haystack_length) { if (*arg4 == '1' || ctoupper(*arg4) == 'R') // Conduct the search starting at the right side, moving leftward. { // Want it to behave like in this example: If searching for the 2nd occurrence of // FF in the string FFFF, it should find the first two F's, not the middle two: found = tcsrstr(haystack, haystack_length - offset, needle, (StringCaseSenseType)g.StringCaseSense, occurrence_number); } else { // Want it to behave like in this example: If searching for the 2nd occurrence of // FF in the string FFFF, it should find position 3 (the 2nd pair), not position 2: size_t needle_length = ArgLength(3); int i; for (i = 1, found = haystack + offset; ; ++i, found += needle_length) if (!(found = g_tcsstr(found, needle)) || i == occurrence_number) break; } if (found) pos = (int)(found - haystack); // else leave pos set to its default value, -1. } //else offset >= haystack_length, so no match is possible in either left or right mode. } } g_ErrorLevel->Assign(pos < 0 ? ERRORLEVEL_ERROR : ERRORLEVEL_NONE); return output_var->Assign(pos); // Assign() already displayed any error that may have occurred. } case ACT_STRINGREPLACE: return StringReplace(); case ACT_TRANSFORM: return Transform(ARG2, ARG3, ARG4); case ACT_STRINGSPLIT: return StringSplit(ARG1, ARG2, ARG3, ARG4); case ACT_SPLITPATH: return SplitPath(ARG1); case ACT_SORT: return PerformSort(ARG1, ARG2); #ifndef MINIDLL case ACT_PIXELSEARCH: // ArgToInt() works on ARG7 (the color) because any valid BGR or RGB color has 0x00 in the high order byte: return PixelSearch(ArgToInt(3), ArgToInt(4), ArgToInt(5), ArgToInt(6), ArgToInt(7), ArgToInt(8), ARG9, false); case ACT_IMAGESEARCH: return ImageSearch(ArgToInt(3), ArgToInt(4), ArgToInt(5), ArgToInt(6), ARG7); case ACT_PIXELGETCOLOR: return PixelGetColor(ArgToInt(2), ArgToInt(3), ARG4); #endif case ACT_SEND: case ACT_SENDRAW: SendKeys(ARG1, mActionType == ACT_SENDRAW, g.SendMode); return OK; case ACT_SENDINPUT: // Raw mode is supported via {Raw} in ARG1. SendKeys(ARG1, false, g.SendMode == SM_INPUT_FALLBACK_TO_PLAY ? SM_INPUT_FALLBACK_TO_PLAY : SM_INPUT); return OK; case ACT_SENDPLAY: // Raw mode is supported via {Raw} in ARG1. SendKeys(ARG1, false, SM_PLAY); return OK; case ACT_SENDEVENT: SendKeys(ARG1, false, SM_EVENT); return OK; case ACT_CLICK: - return PerformClick(ARG1); + // return PerformClick(ARG1); case ACT_MOUSECLICKDRAG: - return PerformMouse(mActionType, SEVEN_ARGS); + // return PerformMouse(mActionType, SEVEN_ARGS); case ACT_MOUSECLICK: - return PerformMouse(mActionType, THREE_ARGS, _T(""), _T(""), ARG5, ARG7, ARG4, ARG6); + // return PerformMouse(mActionType, THREE_ARGS, _T(""), _T(""), ARG5, ARG7, ARG4, ARG6); case ACT_MOUSEMOVE: // return PerformMouse(mActionType, _T(""), ARG1, ARG2, _T(""), _T(""), ARG3, ARG4); - return OK; + case ACT_MOUSEGETPOS: - return MouseGetPos(ArgToUInt(5)); - + // return MouseGetPos(ArgToUInt(5)); + return OK; case ACT_WINACTIVATE: case ACT_WINACTIVATEBOTTOM: - if (WinActivate(g, FOUR_ARGS, mActionType == ACT_WINACTIVATEBOTTOM)) + /* if (WinActivate(g, FOUR_ARGS, mActionType == ACT_WINACTIVATEBOTTOM)) // 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; + */ return OK; case ACT_WINMINIMIZE: case ACT_WINMAXIMIZE: case ACT_WINRESTORE: case ACT_WINHIDE: case ACT_WINSHOW: case ACT_WINCLOSE: case ACT_WINKILL: - { + return OK ; + /* { // 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(ARG1, _T("ahk_group"), 9) || *ARG2 || *ARG4); // 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 (mActionType == ACT_WINCLOSE || mActionType == ACT_WINKILL) // ARG3 is contains the wait time. { if (*ARG3 && !(wait_time = (int)(1000 * ArgToDouble(3))) ) wait_time = 500; // Legacy (prior to supporting floating point): 0 is defined as 500ms, which seems more useful than a true zero. if (*ARG5) is_ahk_group = false; // Override the default. } else if (*ARG3) is_ahk_group = false; // Override the default. // Act upon all members of this group (WinText/ExcludeTitle/ExcludeText are ignored in this mode). if (is_ahk_group && (group = g_script.FindGroup(omit_leading_whitespace(ARG1 + 9)))) // Assign. return group->ActUponAll(mActionType, wait_time); // It will do DoWinDelay if appropriate. //else try to act upon it as though "ahk_group something" is a literal window title. // Since above didn't return, it's not "ahk_group", so do the normal single-window behavior. if (mActionType == ACT_WINCLOSE || mActionType == ACT_WINKILL) { if (WinClose(g, ARG1, ARG2, wait_time, ARG4, ARG5, mActionType == ACT_WINKILL)) // It closed something. DoWinDelay; return OK; } else return PerformShowWindow(mActionType, FOUR_ARGS); } - + */ case ACT_ENVGET: - return EnvGet(ARG2); + // return EnvGet(ARG2); case ACT_ENVSET: // MSDN: "If [the 2nd] parameter is NULL, the variable is deleted from the current process’s environment." // My: Though it seems okay, for now, just to set it to be blank if the user omitted the 2nd param or // left it blank (AutoIt3 does this too). Also, no checking is currently done to ensure that ARG2 // isn't longer than 32K, since future OSes may support longer env. vars. SetEnvironmentVariable() // might return 0(fail) in that case anyway. Also, ARG1 may be a dereferenced variable that resolves // to the name of an Env. Variable. In any case, this name need not correspond to any existing // variable name within the script (i.e. script variables and env. variables aren't tied to each other // in any way). This seems to be the most flexible approach, but are there any shortcomings? // The only one I can think of is that if the script tries to fetch the value of an env. var (perhaps // one that some other spawned program changed), and that var's name corresponds to the name of a // script var, the script var's value (if non-blank) will be fetched instead. // Note: It seems, at least under WinXP, that env variable names can contain spaces. So it's best // not to validate ARG1 the same way we validate script variables (i.e. just let\ // SetEnvironmentVariable()'s return value determine whether there's an error). However, I just // realized that it's impossible to "retrieve" the value of an env var that has spaces (until now, // since the EnvGet command is available). - return SetErrorLevelOrThrowBool(!SetEnvironmentVariable(ARG1, ARG2)); - - case ACT_ENVUPDATE: + // return SetErrorLevelOrThrowBool(!SetEnvironmentVariable(ARG1, ARG2)); + return OK ; + case ACT_ENVUPDATE: /* { // From the AutoIt3 source: // AutoIt3 uses SMTO_BLOCK (which prevents our thread from doing anything during the call) // vs. SMTO_NORMAL. Since I'm not sure why, I'm leaving it that way for now: ULONG_PTR nResult; return SetErrorLevelOrThrowBool(!SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)_T("Environment"), SMTO_BLOCK, 15000, &nResult)); - } + } */ case ACT_URLDOWNLOADTOFILE: - return URLDownloadToFile(TWO_ARGS); + // return URLDownloadToFile(TWO_ARGS); - case ACT_RUNAS: + case ACT_RUNAS: /* if (!g_os.IsWin2000orLater()) // Do nothing if the OS doesn't support it. return OK; StringTCharToWChar(ARG1, g_script.mRunAsUser); StringTCharToWChar(ARG2, g_script.mRunAsPass); - StringTCharToWChar(ARG3, g_script.mRunAsDomain); + StringTCharToWChar(ARG3, g_script.mRunAsDomain); */ return OK; - case ACT_RUN: + case ACT_RUN: /* { bool use_el = tcscasestr(ARG3, _T("UseErrorLevel")); result = g_script.ActionExec(ARG1, NULL, ARG2, !use_el, ARG3, NULL, use_el, true, ARGVAR4); // Be sure to pass NULL for 2nd param. if (use_el) // The special string ERROR is used, rather than a number like 1, because currently // RunWait might in the future be able to return any value, including 259 (STATUS_PENDING). result = g_ErrorLevel->Assign(result ? ERRORLEVEL_NONE : _T("ERROR")); // Otherwise, if result == FAIL, above already displayed the error (or threw an exception). return result; - } + } */ case ACT_RUNWAIT: case ACT_CLIPWAIT: case ACT_KEYWAIT: case ACT_WINWAIT: case ACT_WINWAITCLOSE: case ACT_WINWAITACTIVE: case ACT_WINWAITNOTACTIVE: - return PerformWait(); + // return PerformWait(); case ACT_WINMOVE: - return mArgc > 2 ? WinMove(EIGHT_ARGS) : WinMove(_T(""), _T(""), ARG1, ARG2); + // return mArgc > 2 ? WinMove(EIGHT_ARGS) : WinMove(_T(""), _T(""), ARG1, ARG2); case ACT_WINMENUSELECTITEM: - return WinMenuSelectItem(ELEVEN_ARGS); + // return WinMenuSelectItem(ELEVEN_ARGS); case ACT_CONTROLSEND: case ACT_CONTROLSENDRAW: - return ControlSend(SIX_ARGS, mActionType == ACT_CONTROLSENDRAW); + // return ControlSend(SIX_ARGS, mActionType == ACT_CONTROLSENDRAW); case ACT_CONTROLCLICK: - if ( !(vk = ConvertMouseButton(ARG4)) ) // Treats blank as "Left". - return LineError(ERR_PARAM4_INVALID, FAIL, ARG4); - return ControlClick(vk, *ARG5 ? ArgToInt(5) : 1, ARG6, ARG1, ARG2, ARG3, ARG7, ARG8); + // if ( !(vk = ConvertMouseButton(ARG4)) ) // Treats blank as "Left". + // return LineError(ERR_PARAM4_INVALID, FAIL, ARG4); + // return ControlClick(vk, *ARG5 ? ArgToInt(5) : 1, ARG6, ARG1, ARG2, ARG3, ARG7, ARG8); case ACT_CONTROLMOVE: - return ControlMove(NINE_ARGS); + // return ControlMove(NINE_ARGS); case ACT_CONTROLGETPOS: - return ControlGetPos(ARG5, ARG6, ARG7, ARG8, ARG9); + // return ControlGetPos(ARG5, ARG6, ARG7, ARG8, ARG9); case ACT_CONTROLGETFOCUS: - return ControlGetFocus(ARG2, ARG3, ARG4, ARG5); + // return ControlGetFocus(ARG2, ARG3, ARG4, ARG5); case ACT_CONTROLFOCUS: - return ControlFocus(FIVE_ARGS); + // return ControlFocus(FIVE_ARGS); case ACT_CONTROLSETTEXT: - return ControlSetText(SIX_ARGS); + // return ControlSetText(SIX_ARGS); case ACT_CONTROLGETTEXT: - return ControlGetText(ARG2, ARG3, ARG4, ARG5, ARG6); + // return ControlGetText(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_CONTROL: - return Control(SEVEN_ARGS); + // return Control(SEVEN_ARGS); case ACT_CONTROLGET: - return ControlGet(ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8); + // return ControlGet(ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8); case ACT_STATUSBARGETTEXT: - return StatusBarGetText(ARG2, ARG3, ARG4, ARG5, ARG6); + // return StatusBarGetText(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_STATUSBARWAIT: - return StatusBarWait(EIGHT_ARGS); + // return StatusBarWait(EIGHT_ARGS); case ACT_POSTMESSAGE: case ACT_SENDMESSAGE: - return ScriptPostSendMessage(mActionType == ACT_SENDMESSAGE); + // return ScriptPostSendMessage(mActionType == ACT_SENDMESSAGE); case ACT_PROCESS: - return ScriptProcess(THREE_ARGS); + // return ScriptProcess(THREE_ARGS); case ACT_WINSET: - return WinSet(SIX_ARGS); + // return WinSet(SIX_ARGS); case ACT_WINSETTITLE: - return mArgc > 1 ? WinSetTitle(FIVE_ARGS) : WinSetTitle(_T(""), _T(""), ARG1); + // return mArgc > 1 ? WinSetTitle(FIVE_ARGS) : WinSetTitle(_T(""), _T(""), ARG1); case ACT_WINGETTITLE: - return WinGetTitle(ARG2, ARG3, ARG4, ARG5); + // return WinGetTitle(ARG2, ARG3, ARG4, ARG5); case ACT_WINGETCLASS: - return WinGetClass(ARG2, ARG3, ARG4, ARG5); + // return WinGetClass(ARG2, ARG3, ARG4, ARG5); case ACT_WINGET: - return WinGet(ARG2, ARG3, ARG4, ARG5, ARG6); + // return WinGet(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_WINGETTEXT: - return WinGetText(ARG2, ARG3, ARG4, ARG5); + // return WinGetText(ARG2, ARG3, ARG4, ARG5); case ACT_WINGETPOS: - return WinGetPos(ARG5, ARG6, ARG7, ARG8); + // return WinGetPos(ARG5, ARG6, ARG7, ARG8); case ACT_SYSGET: - return SysGet(ARG2, ARG3); - - case ACT_WINMINIMIZEALL: + // return SysGet(ARG2, ARG3); + return OK ; + case ACT_WINMINIMIZEALL: /* PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 419, 0); DoWinDelay; - return OK; - case ACT_WINMINIMIZEALLUNDO: + return OK; */ + case ACT_WINMINIMIZEALLUNDO: /* PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 416, 0); - DoWinDelay; + DoWinDelay; */ return OK; case ACT_ONEXIT: if (!*ARG1) // Reset to normal Exit behavior. { g_script.mOnExitLabel = NULL; return OK; } // If it wasn't resolved at load-time, it must be a variable reference: if ( !(target_label = (Label *)mAttribute) ) if ( !(target_label = g_script.FindLabel(ARG1)) ) return LineError(ERR_NO_LABEL, FAIL, ARG1); g_script.mOnExitLabel = target_label; return OK; #ifndef MINIDLL case ACT_HOTKEY: // mAttribute is the label resolved at loadtime, if available (for performance). - return Hotkey::Dynamic(THREE_ARGS, (Label *)mAttribute); + // return Hotkey::Dynamic(THREE_ARGS, (Label *)mAttribute); #endif - case ACT_SETTIMER: // A timer is being created, changed, or enabled/disabled. + case ACT_SETTIMER: /* // A timer is being created, changed, or enabled/disabled. // Note that only one timer per label is allowed because the label is the unique identifier // that allows us to figure out whether to "update or create" when searching the list of timers. if ( !(target_label = (Label *)mAttribute) ) // Since it wasn't resolved at load-time, it must be a variable reference. if ( !(target_label = (*ARG1 ? g_script.FindLabel(ARG1) : g.CurrentLabel)) ) return LineError(ERR_NO_LABEL, FAIL, ARG1); // And don't update mAttribute (leave it NULL) because we want ARG1 to be dynamically resolved // every time the command is executed (in case the contents of the referenced variable change). // In the data structure that holds the timers, we store the target label rather than the target // line so that a label can be registered independently as a timers even if there another label // that points to the same line such as in this example: // Label1:: // Label2:: // ... // return if (*ARG2) { toggle = Line::ConvertOnOff(ARG2); if (!toggle && !IsPureNumeric(ARG2, true, true, true)) // Allow it to be neg. or floating point at runtime. return LineError(ERR_PARAM2_INVALID, FAIL, ARG2); } else toggle = TOGGLE_INVALID; // Below relies on distinguishing a true empty string from one that is sent to the function // as empty as a signal. Don't change it without a full understanding because it's likely // to break compatibility or something else: switch(toggle) { case TOGGLED_ON: case TOGGLED_OFF: g_script.UpdateOrCreateTimer(target_label, _T(""), ARG3, toggle == TOGGLED_ON, false); break; // Timer is always (re)enabled when ARG2 specifies a numeric period or is blank + there's no ARG3. // If ARG2 is blank but ARG3 (priority) isn't, tell it to update only the priority and nothing else: default: g_script.UpdateOrCreateTimer(target_label, ARG2, ARG3, true, !*ARG2 && *ARG3); - } + } */ return OK; case ACT_CRITICAL: { // v1.0.46: When the current thread is critical, have the script check messages less often to // reduce situations where an OnMesage or GUI message must be discarded due to "thread already // running". Using 16 rather than the default of 5 solves reliability problems in a custom-menu-draw // script and probably many similar scripts -- even when the system is under load (though 16 might not // be enough during an extreme load depending on the exact preemption/timeslice dynamics involved). // DON'T GO TOO HIGH because this setting reduces response time for ALL messages, even those that // don't launch script threads (especially painting/drawing and other screen-update events). // Future enhancement: Could allow the value of 16 to be customized via something like "Critical 25". // However, it seems best not to allow it to go too high (say, no more than 2000) because that would // cause the script to completely hang if the critical thread never finishes, or takes a long time // to finish. A configurable limit might also allow things to work better on Win9x because it has // a bigger tickcount granularity. // Some hardware has a tickcount granularity of 15 instead of 10, so this covers more variations. DWORD peek_frequency_when_critical_is_on = 16; // Set default. See below. // v1.0.48: Below supports "Critical 0" as meaning "Off" to improve compatibility with A_IsCritical. // In fact, for performance, only the following are no recognized as turning on Critical: // - "On" // - "" // - Integer other than 0. // Everything else, if considered to be "Off", including "Off", "Any non-blank string that // doesn't start with a non-zero number", and zero itself. g.ThreadIsCritical = !*ARG1 // i.e. a first arg that's omitted or blank is the same as "ON". See comments above. || !_tcsicmp(ARG1, _T("ON")) || (peek_frequency_when_critical_is_on = ArgToUInt(1)); // Non-zero integer also turns it on. Relies on short-circuit boolean order. if (g.ThreadIsCritical) // Critical has been turned on. (For simplicity even if it was already on, the following is done.) { g.PeekFrequency = peek_frequency_when_critical_is_on; g.AllowThreadToBeInterrupted = false; g.LinesPerCycle = -1; // v1.0.47: It seems best to ensure SetBatchLines -1 is in effect because g.IntervalBeforeRest = -1; // otherwise it may check messages during the interval that it isn't supposed to. } else // Critical has been turned off. { // Since Critical is being turned off, allow thread to be immediately interrupted regardless of // any "Thread Interrupt" settings. g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; g.AllowThreadToBeInterrupted = true; } // Once ACT_CRITICAL returns, the thread's interruptibility has been explicitly set; so the script // is now in charge of managing this thread's interruptibility. return OK; } case ACT_THREAD: switch (ConvertThreadCommand(ARG1)) { case THREAD_CMD_PRIORITY: g.Priority = ArgToInt(2); break; case THREAD_CMD_INTERRUPT: // If either one is blank, leave that setting as it was before. if (*ARG1) g_script.mUninterruptibleTime = ArgToInt(2); // 32-bit (for compatibility with DWORDs returned by GetTickCount). if (*ARG2) g_script.mUninterruptedLineCountMax = ArgToInt(3); // 32-bit also, to help performance (since huge values seem unnecessary). break; case THREAD_CMD_NOTIMERS: g.AllowTimers = (*ARG2 && ArgToInt64(2) == 0); break; // If invalid command, do nothing since that is always caught at load-time unless the command // is in a variable reference (very rare in this case). } return OK; - case ACT_GROUPADD: // Adding a WindowSpec *to* a group, not adding a group. + case ACT_GROUPADD: /* // Adding a WindowSpec *to* a group, not adding a group. { if ( !(group = (WinGroup *)mAttribute) ) if ( !(group = g_script.FindGroup(ARG1, true)) ) // Last parameter -> create-if-not-found. return FAIL; // It already displayed the error for us. target_label = NULL; if (*ARG4) { if ( !(target_label = (Label *)mRelatedLine) ) // Jump target hasn't been resolved yet, probably due to it being a deref. if ( !(target_label = g_script.FindLabel(ARG4)) ) return LineError(ERR_NO_LABEL, FAIL, ARG4); // Can't do this because the current line won't be the launching point for the // Gosub. Instead, the launching point will be the GroupActivate rather than the // GroupAdd, so it will be checked by the GroupActivate or not at all (since it's // not that important in the case of a Gosub -- it's mostly for Goto's): //return IsJumpValid(label->mJumpToLine); group->mJumpToLabel = target_label; } return group->AddWindow(ARG2, ARG3, ARG5, ARG6); - } + } */ // Note ACT_GROUPACTIVATE is handled by ExecUntil(), since it's better suited to do the Gosub. - case ACT_GROUPDEACTIVATE: + case ACT_GROUPDEACTIVATE: /* if ( !(group = (WinGroup *)mAttribute) ) group = g_script.FindGroup(ARG1); if (group) group->Deactivate(*ARG2 && !_tcsicmp(ARG2, _T("R"))); // Note: It will take care of DoWinDelay if needed. - //else nonexistent group: By design, do nothing. + //else nonexistent group: By design, do nothing. */ return OK; - case ACT_GROUPCLOSE: + case ACT_GROUPCLOSE: /* if ( !(group = (WinGroup *)mAttribute) ) group = g_script.FindGroup(ARG1); if (group) if (*ARG2 && !_tcsicmp(ARG2, _T("A"))) group->ActUponAll(ACT_WINCLOSE, 0); // Note: It will take care of DoWinDelay if needed. else group->CloseAndGoToNext(*ARG2 && !_tcsicmp(ARG2, _T("R"))); // Note: It will take care of DoWinDelay if needed. - //else nonexistent group: By design, do nothing. + //else nonexistent group: By design, do nothing. */ return OK; case ACT_GETKEYSTATE: - return GetKeyJoyState(ARG2, ARG3); - + // return GetKeyJoyState(ARG2, ARG3); + return OK ; case ACT_RANDOM: { if (!output_var) // v1.0.42.03: Special mode to change the seed. { init_genrand(ArgToUInt(2)); // It's documented that an unsigned 32-bit number is required. return OK; } bool use_float = IsPureNumeric(ARG2, true, false, true) == PURE_FLOAT || IsPureNumeric(ARG3, true, false, true) == PURE_FLOAT; if (use_float) { double rand_min = *ARG2 ? ArgToDouble(2) : 0; double rand_max = *ARG3 ? ArgToDouble(3) : INT_MAX; // Seems best not to use ErrorLevel for this command at all, since silly cases // such as Max > Min are too rare. Swap the two values instead. if (rand_min > rand_max) { double rand_swap = rand_min; rand_min = rand_max; rand_max = rand_swap; } return output_var->Assign((genrand_real1() * (rand_max - rand_min)) + rand_min); } else // Avoid using floating point, where possible, which may improve speed a lot more than expected. { int rand_min = *ARG2 ? ArgToInt(2) : 0; int rand_max = *ARG3 ? ArgToInt(3) : INT_MAX; // Seems best not to use ErrorLevel for this command at all, since silly cases // such as Max > Min are too rare. Swap the two values instead. if (rand_min > rand_max) { int rand_swap = rand_min; rand_min = rand_max; rand_max = rand_swap; } // Do NOT use genrand_real1() 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: // AutoIt3: __int64 is needed here to do the proper conversion from unsigned long to signed long: return output_var->Assign( (int)(__int64(genrand_int32() % ((__int64)rand_max - rand_min + 1)) + rand_min) ); } } case ACT_DRIVESPACEFREE: return DriveSpace(ARG2, true); case ACT_DRIVE: - return Drive(THREE_ARGS); - + // return Drive(THREE_ARGS); + return OK ; case ACT_DRIVEGET: return DriveGet(ARG2, ARG3); case ACT_SOUNDGET: - case ACT_SOUNDSET: + case ACT_SOUNDSET: /* device_id = *ARG4 ? ArgToInt(4) - 1 : 0; if (device_id < 0) device_id = 0; instance_number = 1; // Set default. component_type = *ARG2 ? SoundConvertComponentType(ARG2, &instance_number) : MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; return SoundSetGet(mActionType == ACT_SOUNDGET ? NULL : ARG1 , component_type, instance_number // Which instance of this component, 1 = first , *ARG3 ? SoundConvertControlType(ARG3) : MIXERCONTROL_CONTROLTYPE_VOLUME // Default , (UINT)device_id); - + */ case ACT_SOUNDGETWAVEVOLUME: - case ACT_SOUNDSETWAVEVOLUME: + case ACT_SOUNDSETWAVEVOLUME: /* device_id = *ARG2 ? ArgToInt(2) - 1 : 0; if (device_id < 0) device_id = 0; return (mActionType == ACT_SOUNDGETWAVEVOLUME) ? SoundGetWaveVolume((HWAVEOUT)device_id) : SoundSetWaveVolume(ARG1, (HWAVEOUT)device_id); - + */ case ACT_SOUNDBEEP: // For simplicity and support for future/greater capabilities, no range checking is done. // It simply calls the function with the two DWORD values provided. It avoids setting // ErrorLevel because failure is rare and also because a script might want play a beep // right before displaying an error dialog that uses the previous value of ErrorLevel. - Beep(*ARG1 ? ArgToUInt(1) : 523, *ARG2 ? ArgToUInt(2) : 150); + // Beep(*ARG1 ? ArgToUInt(1) : 523, *ARG2 ? ArgToUInt(2) : 150); return OK; case ACT_SOUNDPLAY: - return SoundPlay(ARG1, *ARG2 && !_tcsicmp(ARG2, _T("wait")) || !_tcsicmp(ARG2, _T("1"))); + // return SoundPlay(ARG1, *ARG2 && !_tcsicmp(ARG2, _T("wait")) || !_tcsicmp(ARG2, _T("1"))); case ACT_FILEAPPEND: // Uses the read-file loop's current item filename was explicitly leave blank (i.e. not just // a reference to a variable that's blank): - return FileAppend(ARG2, ARG1, (mArgc < 2) ? g.mLoopReadFile : NULL); + // return FileAppend(ARG2, ARG1, (mArgc < 2) ? g.mLoopReadFile : NULL); case ACT_FILEREAD: - return FileRead(ARG2); + // return FileRead(ARG2); case ACT_FILEREADLINE: - return FileReadLine(ARG2, ARG3); + // return FileReadLine(ARG2, ARG3); case ACT_FILEDELETE: - return FileDelete(); + // return FileDelete(); case ACT_FILERECYCLE: - return FileRecycle(ARG1); + // return FileRecycle(ARG1); case ACT_FILERECYCLEEMPTY: - return FileRecycleEmpty(ARG1); + // return FileRecycleEmpty(ARG1); #ifndef MINIDLL case ACT_FILEINSTALL: - return FileInstall(THREE_ARGS); + // return FileInstall(THREE_ARGS); #endif - case ACT_FILECOPY: + case ACT_FILECOPY: /* { int error_count = Util_CopyFile(ARG1, ARG2, ArgToInt(3) == 1, false, g.LastError); if (!error_count) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (g_script.mIsAutoIt2) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // For backward compatibility with v2. return SetErrorLevelOrThrowInt(error_count); - } + } */ case ACT_FILEMOVE: - return SetErrorLevelOrThrowInt(Util_CopyFile(ARG1, ARG2, ArgToInt(3) == 1, true, g.LastError)); + // return SetErrorLevelOrThrowInt(Util_CopyFile(ARG1, ARG2, ArgToInt(3) == 1, true, g.LastError)); case ACT_FILECOPYDIR: - return SetErrorLevelOrThrowBool(!Util_CopyDir(ARG1, ARG2, ArgToInt(3) == 1)); - case ACT_FILEMOVEDIR: + // return SetErrorLevelOrThrowBool(!Util_CopyDir(ARG1, ARG2, ArgToInt(3) == 1)); + case ACT_FILEMOVEDIR: /* if (ctoupper(*ARG3) == '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 SetErrorLevelOrThrowBool(!MoveFile(ARG1, ARG2)); } // Otherwise: return SetErrorLevelOrThrowBool(!Util_MoveDir(ARG1, ARG2, ArgToInt(3))); - + */ case ACT_FILECREATEDIR: - return FileCreateDir(ARG1); + // return FileCreateDir(ARG1); case ACT_FILEREMOVEDIR: - return SetErrorLevelOrThrowBool(!*ARG1 // Consider an attempt to create or remove a blank dir to be an error. - || !Util_RemoveDir(ARG1, ArgToInt(2) == 1)); // Relies on short-circuit evaluation. + // return SetErrorLevelOrThrowBool(!*ARG1 // Consider an attempt to create or remove a blank dir to be an error. + // || !Util_RemoveDir(ARG1, ArgToInt(2) == 1)); // Relies on short-circuit evaluation. case ACT_FILEGETATTRIB: // The specified ARG, if non-blank, takes precedence over the file-loop's file (if any): #define USE_FILE_LOOP_FILE_IF_ARG_BLANK(arg) (*arg ? arg : (g.mLoopFile ? g.mLoopFile->cFileName : _T(""))) - return FileGetAttrib(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); + // return FileGetAttrib(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); case ACT_FILESETATTRIB: FileSetAttrib(ARG1, USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), ConvertLoopMode(ARG3), ArgToInt(4) == 1); - return !g.ThrownToken ? OK : FAIL; + // return !g.ThrownToken ? OK : FAIL; case ACT_FILEGETTIME: - return FileGetTime(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), *ARG3); + // return FileGetTime(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), *ARG3); case ACT_FILESETTIME: FileSetTime(ARG1, USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), *ARG3, ConvertLoopMode(ARG4), ArgToInt(5) == 1); - return !g.ThrownToken ? OK : FAIL; + // return !g.ThrownToken ? OK : FAIL; case ACT_FILEGETSIZE: - return FileGetSize(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), ARG3); + // return FileGetSize(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), ARG3); case ACT_FILEGETVERSION: - return FileGetVersion(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); + // return FileGetVersion(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); case ACT_SETWORKINGDIR: - SetWorkingDir(ARG1); - return !g.ThrownToken ? OK : FAIL; + // SetWorkingDir(ARG1); + // return !g.ThrownToken ? OK : FAIL; + return OK ; #ifndef MINIDLL case ACT_FILESELECTFILE: - return FileSelectFile(ARG2, ARG3, ARG4, ARG5); + // return FileSelectFile(ARG2, ARG3, ARG4, ARG5); case ACT_FILESELECTFOLDER: - return FileSelectFolder(ARG2, ARG3, ARG4); + // return FileSelectFolder(ARG2, ARG3, ARG4); #endif case ACT_FILEGETSHORTCUT: - return FileGetShortcut(ARG1); + // return FileGetShortcut(ARG1); case ACT_FILECREATESHORTCUT: - return FileCreateShortcut(NINE_ARGS); + // return FileCreateShortcut(NINE_ARGS); #ifndef MINIDLL - case ACT_KEYHISTORY: + case ACT_KEYHISTORY: /* #ifdef ENABLE_KEY_HISTORY_FILE if (*ARG1 || *ARG2) { switch (ConvertOnOffToggle(ARG1)) { case NEUTRAL: case TOGGLE: g_KeyHistoryToFile = !g_KeyHistoryToFile; if (!g_KeyHistoryToFile) KeyHistoryToFile(); // Signal it to close the file, if it's open. break; case TOGGLED_ON: g_KeyHistoryToFile = true; break; case TOGGLED_OFF: g_KeyHistoryToFile = false; KeyHistoryToFile(); // Signal it to close the file, if it's open. break; // We know it's a variable because otherwise the loading validation would have caught it earlier: case TOGGLE_INVALID: return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); } if (*ARG2) // The user also specified a filename, so update the target filename. KeyHistoryToFile(ARG2); return OK; } #endif // Otherwise: return ShowMainWindow(MAIN_MODE_KEYHISTORY, false); // Pass "unrestricted" when the command is explicitly used in the script. - case ACT_LISTLINES: + */ + case ACT_LISTLINES: /* if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) == NEUTRAL ) return ShowMainWindow(MAIN_MODE_LINES, false); // Pass "unrestricted" when the command is explicitly used in the script. // Otherwise: if (g.ListLinesIsEnabled) { // Since ExecUntil() just logged this ListLines On/Off in the line history, remove it to avoid // cluttering the line history with distracting lines that the user probably wouldn't want to see. // Might be especially useful in cases where a timer fires frequently (even if such a timer // used "ListLines Off" as its top line, that line itself would appear very frequently in the line // history). v1.0.48.03: Fixed so that the below executes only when ListLines was previously "On". if (sLogNext > 0) --sLogNext; else sLogNext = LINE_LOG_SIZE - 1; sLog[sLogNext] = NULL; // Without this, one of the lines in the history would be invalid due to the circular nature of the line history array, which would also cause the line history to show the wrong chronological order in some cases. } - g.ListLinesIsEnabled = (toggle == TOGGLED_ON); + g.ListLinesIsEnabled = (toggle == TOGGLED_ON); */ return OK; case ACT_LISTVARS: - return ShowMainWindow(MAIN_MODE_VARS, false); // Pass "unrestricted" when the command is explicitly used in the script. + // return ShowMainWindow(MAIN_MODE_VARS, false); // Pass "unrestricted" when the command is explicitly used in the script. case ACT_LISTHOTKEYS: - return ShowMainWindow(MAIN_MODE_HOTKEYS, false); // Pass "unrestricted" when the command is explicitly used in the script. + // return ShowMainWindow(MAIN_MODE_HOTKEYS, false); // Pass "unrestricted" when the command is explicitly used in the script. #endif // MINIDLL - case ACT_MSGBOX: + case ACT_MSGBOX: /* { int result; #ifndef MINIDLL HWND dialog_owner = THREAD_DIALOG_OWNER; // Resolve macro only once to reduce code size. #else HWND dialog_owner = NULL; #endif // If the MsgBox window can't be displayed for any reason, always return FAIL to // the caller because it would be unsafe to proceed with the execution of the // current script subroutine. For example, if the script contains an IfMsgBox after, // this line, it's result would be unpredictable and might cause the subroutine to perform // the opposite action from what was intended (e.g. Delete vs. don't delete a file). if (!mArgc) // When called explicitly with zero params, it displays this default msg. result = MsgBox(_T("Press OK to continue."), MSGBOX_NORMAL, NULL, 0, dialog_owner); else if (mArgc == 1) // In the special 1-parameter mode, the first param is the prompt. result = MsgBox(ARG1, MSGBOX_NORMAL, NULL, 0, dialog_owner); else result = MsgBox(ARG3, ArgToInt(1), ARG2, ArgToDouble(4), dialog_owner); // dialog_owner passed via parameter to avoid internally-displayed MsgBoxes from being affected by script-thread's owner setting. // Above allows backward compatibility with AutoIt2's param ordering while still // permitting the new method of allowing only a single param. // v1.0.40.01: Rather than displaying another MsgBox in response to a failed attempt to display // a MsgBox, it seems better (less likely to cause trouble) just to abort the thread. This also // solves a double-msgbox issue when the maximum number of MsgBoxes is reached. In addition, the // max-msgbox limit is the most common reason for failure, in which case a warning dialog has // already been displayed, so there is no need to display another: //if (!result) // // It will fail if the text is too large (say, over 150K or so on XP), but that // // has since been fixed by limiting how much it tries to display. // // If there were too many message boxes displayed, it will already have notified // // the user of this via a final MessageBox dialog, so our call here will // // not have any effect. The below only takes effect if MsgBox()'s call to // // MessageBox() failed in some unexpected way: // LineError("The MsgBox could not be displayed."); return result ? OK : FAIL; - } + } */ #ifndef MINIDLL - case ACT_INPUTBOX: + case ACT_INPUTBOX: /* return InputBox(output_var, ARG2, ARG3, ctoupper(*ARG4) == 'H' // 4th is whether to hide input. , *ARG5 ? ArgToInt(5) : INPUTBOX_DEFAULT // Width , *ARG6 ? ArgToInt(6) : INPUTBOX_DEFAULT // Height , *ARG7 ? ArgToInt(7) : INPUTBOX_DEFAULT // Xpos , *ARG8 ? ArgToInt(8) : INPUTBOX_DEFAULT // Ypos // ARG9: future use for Font name & size, e.g. "Courier:8" , ArgToDouble(10) // Timeout , ARG11 // Initial default string for the edit field. - ); + ); */ case ACT_SPLASHTEXTON: - return SplashTextOn(*ARG1 ? ArgToInt(1) : 200, *ARG2 ? ArgToInt(2) : 0, ARG3, ARG4); + // return SplashTextOn(*ARG1 ? ArgToInt(1) : 200, *ARG2 ? ArgToInt(2) : 0, ARG3, ARG4); case ACT_SPLASHTEXTOFF: - DESTROY_SPLASH + // DESTROY_SPLASH return OK; case ACT_PROGRESS: - return Splash(FIVE_ARGS, _T(""), false); // ARG6 is for future use and currently not passed. + // return Splash(FIVE_ARGS, _T(""), false); // ARG6 is for future use and currently not passed. case ACT_SPLASHIMAGE: - return Splash(ARG2, ARG3, ARG4, ARG5, ARG6, ARG1, true); // ARG7 is for future use and currently not passed. + // return Splash(ARG2, ARG3, ARG4, ARG5, ARG6, ARG1, true); // ARG7 is for future use and currently not passed. #endif case ACT_TOOLTIP: - return ToolTip(FOUR_ARGS); + // return ToolTip(FOUR_ARGS); #ifndef MINIDLL case ACT_TRAYTIP: - return TrayTip(FOUR_ARGS); + // return TrayTip(FOUR_ARGS); case ACT_INPUT: - return Input(); - + // return Input(); + return OK ; ////////////////////////////////////////////////////////////////////////// #endif - case ACT_COORDMODE: + case ACT_COORDMODE: /* { CoordModeType mode = ConvertCoordMode(ARG2); CoordModeType shift = ConvertCoordModeCmd(ARG1); if (shift != -1 && mode != -1) // Compare directly to -1 because unsigned. g.CoordMode = (g.CoordMode & ~(COORD_MODE_MASK << shift)) | (mode << shift); //else too rare to report an error, since load-time validation normally catches it. return OK; - } + } */ - case ACT_SETDEFAULTMOUSESPEED: + case ACT_SETDEFAULTMOUSESPEED: /* g.DefaultMouseSpeed = (UCHAR)ArgToInt(1); // In case it was a deref, force it to be some default value if it's out of range: if (g.DefaultMouseSpeed < 0 || g.DefaultMouseSpeed > MAX_MOUSE_SPEED) - g.DefaultMouseSpeed = DEFAULT_MOUSE_SPEED; + g.DefaultMouseSpeed = DEFAULT_MOUSE_SPEED; */ return OK; case ACT_SENDMODE: - g.SendMode = ConvertSendMode(ARG1, g.SendMode); // Leave value unchanged if ARG1 is invalid. + // g.SendMode = ConvertSendMode(ARG1, g.SendMode); // Leave value unchanged if ARG1 is invalid. return OK; - case ACT_SENDLEVEL: + case ACT_SENDLEVEL: /* { int sendLevel = ArgToInt(1); if (SendLevelIsValid(sendLevel)) g.SendLevel = sendLevel; return OK; } - - case ACT_SETKEYDELAY: + */ + case ACT_SETKEYDELAY: /* if (!_tcsicmp(ARG3, _T("Play"))) { if (*ARG1) g.KeyDelayPlay = ArgToInt(1); if (*ARG2) g.PressDurationPlay = ArgToInt(2); } else { if (*ARG1) g.KeyDelay = ArgToInt(1); if (*ARG2) g.PressDuration = ArgToInt(2); - } + } */ return OK; - case ACT_SETMOUSEDELAY: + case ACT_SETMOUSEDELAY: /* if (!_tcsicmp(ARG2, _T("Play"))) g.MouseDelayPlay = ArgToInt(1); else - g.MouseDelay = ArgToInt(1); + g.MouseDelay = ArgToInt(1); */ return OK; case ACT_SETWINDELAY: - g.WinDelay = ArgToInt(1); + // g.WinDelay = ArgToInt(1); return OK; case ACT_SETCONTROLDELAY: - g.ControlDelay = ArgToInt(1); + // g.ControlDelay = ArgToInt(1); return OK; case ACT_SETBATCHLINES: // This below ensures that IntervalBeforeRest and LinesPerCycle aren't both in effect simultaneously // (i.e. that both aren't greater than -1), even though ExecUntil() has code to prevent a double-sleep // even if that were to happen. - if (tcscasestr(ARG1, _T("ms"))) // This detection isn't perfect, but it doesn't seem necessary to be too demanding. + /* if (tcscasestr(ARG1, _T("ms"))) // This detection isn't perfect, but it doesn't seem necessary to be too demanding. { g.LinesPerCycle = -1; // Disable the old BatchLines method in favor of the new one below. g.IntervalBeforeRest = ArgToInt(1); // If negative, script never rests. If 0, it rests after every line. } else { g.IntervalBeforeRest = -1; // Disable the new method in favor of the old one below: // This value is signed 64-bits to support variable reference (i.e. containing a large int) // the user might throw at it: if ( !(g.LinesPerCycle = ArgToInt64(1)) ) // Don't interpret zero as "infinite" because zero can accidentally // occur if the dereferenced var was blank: g.LinesPerCycle = 10; // The old default, which is retained for compatibility with existing scripts. - } + }*/ return OK; case ACT_SETSTORECAPSLOCKMODE: - if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) - g.StoreCapslockMode = (toggle == TOGGLED_ON); + // if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) + // g.StoreCapslockMode = (toggle == TOGGLED_ON); return OK; - case ACT_SETTITLEMATCHMODE: + case ACT_SETTITLEMATCHMODE: /* switch (ConvertTitleMatchMode(ARG1)) { case FIND_IN_LEADING_PART: g.TitleMatchMode = FIND_IN_LEADING_PART; return OK; case FIND_ANYWHERE: g.TitleMatchMode = FIND_ANYWHERE; return OK; case FIND_REGEX: g.TitleMatchMode = FIND_REGEX; return OK; case FIND_EXACT: g.TitleMatchMode = FIND_EXACT; return OK; case FIND_FAST: g.TitleFindFast = true; return OK; case FIND_SLOW: g.TitleFindFast = false; return OK; } return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); - + */ + return OK ; case ACT_SETFORMAT: // For now, it doesn't seem necessary to have runtime validation of the first parameter. // Just ignore the command if it's not valid: if (!_tcsnicmp(ARG1, _T("Float"), 5)) // "nicmp" vs. "icmp" so that Float and FloatFast are treated the same (loadtime validation already took notice of the Fast flag). { // -2 to allow room for the letter 'f' and the '%' that will be added: if (ArgLength(2) >= _countof(g.FormatFloat) - 2) // A variable that resolved to something too long. return OK; // Seems best not to bother with a runtime error for something so rare. // Make sure the formatted string wouldn't exceed the buffer size: __int64 width = ArgToInt64(2); LPTSTR dot_pos = _tcschr(ARG2, '.'); __int64 precision = dot_pos ? ATOI64(dot_pos + 1) : 0; if (width + precision + 2 > MAX_NUMBER_LENGTH) // +2 to allow room for decimal point itself and leading minus sign. return OK; // Don't change it. // Create as "%ARG2f". Note that %f can handle doubles in MSVC++: _stprintf(g.FormatFloat, _T("%%%s%s%s"), ARG2 , dot_pos ? _T("") : _T(".") // Add a dot if none was specified so that "0" is the same as "0.", which seems like the most user-friendly approach; it's also easier to document in the help file. , IsPureNumeric(ARG2, true, true, true) ? _T("f") : _T("")); // If it's not pure numeric, assume the user already included the desired letter (e.g. SetFormat, Float, 0.6e). } else if (!_tcsnicmp(ARG1, _T("Integer"), 7)) // "nicmp" vs. "icmp" so that Integer and IntegerFast are treated the same (loadtime validation already took notice of the Fast flag). { switch(*ARG2) { case 'd': case 'D': g.FormatInt = 'D'; break; case 'h': case 'H': g.FormatInt = (char) *ARG2; break; // Otherwise, since the first letter isn't recognized, do nothing since 99% of the time such a // probably would be caught at load-time. } } // Otherwise, ignore invalid type at runtime since 99% of the time it would be caught at load-time: return OK; case ACT_FORMATTIME: return FormatTime(ARG2, ARG3); #ifndef MINIDLL case ACT_MENU: - return g_script.PerformMenu(SIX_ARGS); // L17: Changed from FIVE_ARGS to access previously "reserved" arg (for use by Menu,,Icon). + // return g_script.PerformMenu(SIX_ARGS); // L17: Changed from FIVE_ARGS to access previously "reserved" arg (for use by Menu,,Icon). case ACT_GUI: - return g_script.PerformGui(FOUR_ARGS); + // return g_script.PerformGui(FOUR_ARGS); case ACT_GUICONTROL: - return GuiControl(THREE_ARGS); + // return GuiControl(THREE_ARGS); case ACT_GUICONTROLGET: - return GuiControlGet(ARG2, ARG3, ARG4); + // return GuiControlGet(ARG2, ARG3, ARG4); //////////////////////////////////////////////////////////////////////////////////////// // For these, it seems best not to report an error during runtime if there's // an invalid value (e.g. something other than On/Off/Blank) in a param containing // a dereferenced variable, since settings are global and affect all subroutines, // not just the one that we would otherwise report failure for: - case ACT_SUSPEND: + case ACT_SUSPEND: /* switch (ConvertOnOffTogglePermit(ARG1)) { case NEUTRAL: case TOGGLE: ToggleSuspendState(); break; case TOGGLED_ON: if (!g_IsSuspended) ToggleSuspendState(); break; case TOGGLED_OFF: if (g_IsSuspended) ToggleSuspendState(); break; case TOGGLE_PERMIT: // In this case do nothing. The user is just using this command as a flag to indicate that // this subroutine should not be suspended. break; // We know it's a variable because otherwise the loading validation would have caught it earlier: case TOGGLE_INVALID: return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); - } + } */ return OK; #endif //MINIDLL case ACT_PAUSE: - return ChangePauseState(ConvertOnOffToggle(ARG1), (bool)ArgToInt(2)); + // return ChangePauseState(ConvertOnOffToggle(ARG1), (bool)ArgToInt(2)); + return OK ; case ACT_AUTOTRIM: if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) g.AutoTrim = (toggle == TOGGLED_ON); return OK; case ACT_STRINGCASESENSE: if ((g.StringCaseSense = ConvertStringCaseSense(ARG1)) == SCS_INVALID) g.StringCaseSense = SCS_INSENSITIVE; // For simplicity, just fall back to default if value is invalid (normally its caught at load-time; only rarely here). return OK; case ACT_DETECTHIDDENWINDOWS: - if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) - g.DetectHiddenWindows = (toggle == TOGGLED_ON); + // if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) + // g.DetectHiddenWindows = (toggle == TOGGLED_ON); return OK; case ACT_DETECTHIDDENTEXT: - if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) - g.DetectHiddenText = (toggle == TOGGLED_ON); + // if ( (toggle = ConvertOnOff(ARG1, NEUTRAL)) != NEUTRAL ) + // g.DetectHiddenText = (toggle == TOGGLED_ON); return OK; - case ACT_BLOCKINPUT: + case ACT_BLOCKINPUT: /* switch (toggle = ConvertBlockInput(ARG1)) { case TOGGLED_ON: ScriptBlockInput(true); break; case TOGGLED_OFF: ScriptBlockInput(false); break; case TOGGLE_SEND: case TOGGLE_MOUSE: case TOGGLE_SENDANDMOUSE: case TOGGLE_DEFAULT: g_BlockInputMode = toggle; break; #ifndef MINIDLL case TOGGLE_MOUSEMOVE: g_BlockMouseMove = true; Hotkey::InstallMouseHook(); break; case TOGGLE_MOUSEMOVEOFF: g_BlockMouseMove = false; // But the mouse hook is left installed because it might be needed by other things. This approach is similar to that used by the Input command. break; #endif // default (NEUTRAL or TOGGLE_INVALID): do nothing. - } + } */ return OK; //////////////////////////////////////////////////////////////////////////////////////// // For these, it seems best not to report an error during runtime if there's // an invalid value (e.g. something other than On/Off/Blank) in a param containing // a dereferenced variable, since settings are global and affect all subroutines, // not just the one that we would otherwise report failure for: case ACT_SETNUMLOCKSTATE: - return SetToggleState(VK_NUMLOCK, g_ForceNumLock, ARG1); + // return SetToggleState(VK_NUMLOCK, g_ForceNumLock, ARG1); case ACT_SETCAPSLOCKSTATE: - return SetToggleState(VK_CAPITAL, g_ForceCapsLock, ARG1); + // return SetToggleState(VK_CAPITAL, g_ForceCapsLock, ARG1); case ACT_SETSCROLLLOCKSTATE: - return SetToggleState(VK_SCROLL, g_ForceScrollLock, ARG1); + // return SetToggleState(VK_SCROLL, g_ForceScrollLock, ARG1); #ifndef MINIDLL case ACT_EDIT: - g_script.Edit(); + // g_script.Edit(); return OK; #endif case ACT_RELOAD: - g_script.Reload(true); + // g_script.Reload(true); // Even if the reload failed, it seems best to return OK anyway. That way, // the script can take some follow-on action, e.g. it can sleep for 1000 // after issuing the reload command and then take action under the assumption // that the reload didn't work (since obviously if the process and thread // in which the Sleep is running still exist, it didn't work): return OK; - case ACT_SLEEP: + case ACT_SLEEP: /* { // Only support 32-bit values for this command, since it seems unlikely anyone would to have // it sleep more than 24.8 days or so. It also helps performance on 32-bit hardware because // MsgSleep() is so heavily called and checks the value of the first parameter frequently: int sleep_time = ArgToInt(1); // Keep it signed vs. unsigned for backward compatibility (e.g. scripts that do Sleep -1). // Do a true sleep on Win9x because the MsgSleep() method is very inaccurate on Win9x // for some reason (a MsgSleep(1) causes a sleep between 10 and 55ms, for example). // But only do so for short sleeps, for which the user has a greater expectation of // accuracy. UPDATE: Do not change the 25 below without also changing it in Critical's // documentation. if (sleep_time < 25 && sleep_time > 0 && g_os.IsWin9x()) // Ordered for short-circuit performance. v1.0.38.05: Added "sleep_time > 0" so that Sleep -1/0 will work the same on Win9x as it does on other OSes. Sleep(sleep_time); else MsgSleep(sleep_time); return OK; } - + */ case ACT_INIREAD: - return IniRead(ARG2, ARG3, ARG4, ARG5); + // return IniRead(ARG2, ARG3, ARG4, ARG5); case ACT_INIWRITE: - return IniWrite(FOUR_ARGS); + // return IniWrite(FOUR_ARGS); case ACT_INIDELETE: // To preserve maximum compatibility with existing scripts, only send NULL if ARG3 // was explicitly omitted. This is because some older scripts might rely on the // fact that a blank ARG3 does not delete the entire section, but rather does // nothing (that fact is untested): - return IniDelete(ARG1, ARG2, mArgc < 3 ? NULL : ARG3); + // return IniDelete(ARG1, ARG2, mArgc < 3 ? NULL : ARG3); - case ACT_REGREAD: + case ACT_REGREAD: /* if (mArgc < 2 && g.mLoopRegItem) // Uses the registry loop's current item. // If g.mLoopRegItem->name specifies a subkey rather than a value name, do this anyway // so that it will set ErrorLevel to ERROR and set the output variable to be blank. // Also, do not use RegCloseKey() on this, even if it's a remote key, since our caller handles that: return RegRead(g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name); // Otherwise: if (mArgc > 4 || RegConvertValueType(ARG2)) // The obsolete 5-param method (ARG2 is unused). result = RegRead(root_key = RegConvertRootKey(ARG3, &is_remote_registry), ARG4, ARG5); else result = RegRead(root_key = RegConvertRootKey(ARG2, &is_remote_registry), ARG3, ARG4); if (is_remote_registry && root_key) // Never try to close local root keys, which the OS keeps always-open. RegCloseKey(root_key); - return result; - case ACT_REGWRITE: + return result; */ + case ACT_REGWRITE: /* if (mArgc < 2 && g.mLoopRegItem) // Uses the registry loop's current item. // If g.mLoopRegItem->name specifies a subkey rather than a value name, do this anyway // so that it will set ErrorLevel to ERROR. An error will also be indicated if // g.mLoopRegItem->type is an unsupported type: return RegWrite(g.mLoopRegItem->type, g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name, ARG1); // Otherwise: result = RegWrite(RegConvertValueType(ARG1), root_key = RegConvertRootKey(ARG2, &is_remote_registry) , ARG3, ARG4, ARG5); // If RegConvertValueType(ARG1) yields REG_NONE, RegWrite() will set ErrorLevel rather than displaying a runtime error. if (is_remote_registry && root_key) // Never try to close local root keys, which the OS keeps always-open. RegCloseKey(root_key); - return result; - case ACT_REGDELETE: + return result; */ + case ACT_REGDELETE: /* if (mArgc < 1 && g.mLoopRegItem) // Uses the registry loop's current item. { // In this case, if the current reg item is a value, just delete it normally. // But if it's a subkey, append it to the dir name so that the proper subkey // will be deleted as the user intended: if (g.mLoopRegItem->type == REG_SUBKEY) { sntprintf(buf_temp, _countof(buf_temp), _T("%s\\%s"), g.mLoopRegItem->subkey, g.mLoopRegItem->name); return RegDelete(g.mLoopRegItem->root_key, buf_temp, _T("")); } else return RegDelete(g.mLoopRegItem->root_key, g.mLoopRegItem->subkey, g.mLoopRegItem->name); } // Otherwise: result = RegDelete(root_key = RegConvertRootKey(ARG1, &is_remote_registry), ARG2, ARG3); if (is_remote_registry && root_key) // Never try to close local root keys, which the OS always keeps open. RegCloseKey(root_key); return result; - - case ACT_OUTPUTDEBUG: + */ + case ACT_OUTPUTDEBUG:/* #ifndef CONFIG_DEBUGGER OutputDebugString(ARG1); // It does not return a value for the purpose of setting ErrorLevel. #else g_Debugger.OutputDebug(ARG1); -#endif +#endif */ return OK; case ACT_SHUTDOWN: - return Util_Shutdown(ArgToInt(1)) ? OK : FAIL; // Range of ARG1 is not validated in case other values are supported in the future. + // return Util_Shutdown(ArgToInt(1)) ? OK : FAIL; // Range of ARG1 is not validated in case other values are supported in the future. #ifdef MINIDLL case ACT_IMAGESEARCH: case ACT_PIXELGETCOLOR: case ACT_HOTKEY: case ACT_FILEINSTALL: case ACT_FILESELECTFILE: case ACT_FILESELECTFOLDER: case ACT_KEYHISTORY: case ACT_LISTLINES: case ACT_LISTVARS: case ACT_LISTHOTKEYS: case ACT_INPUTBOX: case ACT_SPLASHTEXTON: case ACT_SPLASHTEXTOFF: case ACT_PROGRESS: case ACT_SPLASHIMAGE: case ACT_TRAYTIP: case ACT_INPUT: case ACT_MENU: case ACT_GUI: case ACT_GUICONTROL: case ACT_GUICONTROLGET: case ACT_SUSPEND: case TOGGLE_MOUSEMOVE: case TOGGLE_MOUSEMOVEOFF: case ACT_EDIT: return LineError(_T("Command is not supported by AutoHotkeyMini.dll\n\nThe current Thread will exit.")); //return OK; //do not show error for not supported commands #endif case ACT_FILEENCODING: UINT new_encoding = ConvertFileEncoding(ARG1); if (new_encoding == -1) return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); // Probably a variable, otherwise load-time validation would've caught it. g.Encoding = new_encoding; return OK; } // switch() // Since above didn't return, this line's mActionType isn't handled here, // so caller called it wrong. ACT_INVALID should be impossible because // Script::AddLine() forbids it. #ifdef _DEBUG return LineError(_T("DEBUG: Perform(): Unhandled action type.")); #else return FAIL; #endif } ResultType Line::Deref(Var *aOutputVar, LPTSTR aBuf) // Similar to ExpandArg(), except it parses and expands all variable references contained in aBuf. { aOutputVar = aOutputVar->ResolveAlias(); // Necessary for proper detection below of whether it's invalidly used as a source for itself. // This transient variable is used resolving environment variables that don't already exist // in the script's variable list (due to the fact that they aren't directly referenced elsewhere // in the script): TCHAR var_name[MAX_VAR_NAME_LENGTH + 1] = _T(""); Var *var; VarSizeType expanded_length; size_t var_name_length; LPTSTR cp, cp1, dest; // Do two passes: // #1: Calculate the space needed so that aOutputVar can be given more capacity if necessary. // #2: Expand the contents of aBuf into aOutputVar. for (int which_pass = 0; which_pass < 2; ++which_pass) { if (which_pass) // Starting second pass. { // Set up aOutputVar, enlarging it if necessary. If it is of type VAR_CLIPBOARD, // this call will set up the clipboard for writing: if (aOutputVar->AssignString(NULL, expanded_length) != OK) return FAIL; dest = aOutputVar->Contents(); // Init, and for performance. } else // First pass. expanded_length = 0; // Init prior to accumulation. for (cp = aBuf; ; ++cp) // Increment to skip over the deref/escape just found by the inner for(). { // Find the next escape char or deref symbol: for (; *cp && *cp != g_EscapeChar && *cp != g_DerefChar; ++cp) { if (which_pass) // 2nd pass *dest++ = *cp; // Copy all non-variable-ref characters literally. else // just accumulate the length ++expanded_length; } if (!*cp) // End of string while scanning/copying. The current pass is now complete. break; if (*cp == g_EscapeChar) { if (which_pass) // 2nd pass { cp1 = cp + 1; switch (*cp1) // See ConvertEscapeSequences() for more details. { // Only lowercase is recognized for these: case 'a': *dest = '\a'; break; // alert (bell) character case 'b': *dest = '\b'; break; // backspace case 'f': *dest = '\f'; break; // formfeed case 'n': *dest = '\n'; break; // newline case 'r': *dest = '\r'; break; // carriage return case 't': *dest = '\t'; break; // horizontal tab case 'v': *dest = '\v'; break; // vertical tab default: *dest = *cp1; // These other characters are resolved just as they are, including '\0'. } ++dest; } else ++expanded_length; // Increment cp here and it will be incremented again by the outer loop, i.e. +2. // In other words, skip over the escape character, treating it and its target character // as a single character. ++cp; continue; } // Otherwise, it's a dereference symbol, so calculate the size of that variable's contents // and add that to expanded_length (or copy the contents into aOutputVar if this is the // second pass). // Find the reference's ending symbol (don't bother with catching escaped deref chars here // -- e.g. %MyVar`% -- since it seems too troublesome to justify given how extremely rarely // it would be an issue): for (cp1 = cp + 1; *cp1 && *cp1 != g_DerefChar; ++cp1); if (!*cp1) // Since end of string was found, this deref is not correctly terminated. continue; // For consistency, omit it entirely. var_name_length = cp1 - cp - 1; if (var_name_length && var_name_length <= MAX_VAR_NAME_LENGTH) { tcslcpy(var_name, cp + 1, var_name_length + 1); // +1 to convert var_name_length to size. // Fixed for v1.0.34: Use FindOrAddVar() vs. FindVar() so that environment or built-in // variables that aren't directly referenced elsewhere in the script will still work: if ( !(var = g_script.FindOrAddVar(var_name, var_name_length)) ) return FAIL; // Above already displayed the error. var = var->ResolveAlias(); // Don't allow the output variable to be read into itself this way because its contents if (var != aOutputVar) // Both of these have had ResolveAlias() called, if required, to make the comparison accurate. { if (which_pass) // 2nd pass dest += var->Get(dest); else // just accumulate the length expanded_length += var->Get(); // Add in the length of the variable's contents. } } // else since the variable name between the deref symbols is blank or too long: for consistency in behavior, // it seems best to omit the dereference entirely (don't put it into aOutputVar). cp = cp1; // For the next loop iteration, continue at the char after this reference's final deref symbol. } // for() } // for() (first and second passes) *dest = '\0'; // Terminate the output variable. aOutputVar->SetCharLength((VarSizeType)_tcslen(aOutputVar->Contents())); // Update to actual in case estimate was too large. return aOutputVar->Close(); // In case it's the clipboard. } LPTSTR Line::LogToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // aBufSize is an int so that any negative values passed in from caller are not lost. // Translates sLog into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. // Caller has ensured that aBuf is non-NULL and that aBufSize is reasonable (at least 256). { LPTSTR aBuf_orig = aBuf; // Store the position of where each retry done by the outer loop will start writing: LPTSTR aBuf_log_start = aBuf + sntprintf(aBuf, aBufSize, _T("Script lines most recently executed (oldest first).") _T(" Press [F5] to refresh. The seconds elapsed between a line and the one after it is in parentheses to") _T(" the right (if not 0). The bottommost line's elapsed time is the number of seconds since it executed.\r\n\r\n")); int i, lines_to_show, line_index, line_index2, space_remaining; // space_remaining must be an int to detect negatives. #ifndef AUTOHOTKEYSC int last_file_index = -1; #endif DWORD elapsed; bool this_item_is_special, next_item_is_special; // In the below, sLogNext causes it to start at the oldest logged line and continue up through the newest: for (lines_to_show = LINE_LOG_SIZE, line_index = sLogNext;;) // Retry with fewer lines in case the first attempt doesn't fit in the buffer. { aBuf = aBuf_log_start; // Reset target position in buffer to the place where log should begin. for (next_item_is_special = false, i = 0; i < lines_to_show; ++i, ++line_index) { if (line_index >= LINE_LOG_SIZE) // wrap around, because sLog is a circular queue line_index -= LINE_LOG_SIZE; // Don't just reset it to zero because an offset larger than one may have been added to it. if (!sLog[line_index]) // No line has yet been logged in this slot. continue; // ACT_LISTLINES and other things might rely on "continue" isntead of halting the loop here. this_item_is_special = next_item_is_special; next_item_is_special = false; // Set default. if (i + 1 < lines_to_show) // There are still more lines to be processed { if (this_item_is_special) // And we know from the above that this special line is not the last line. // Due to the fact that these special lines are usually only useful when they appear at the // very end of the log, omit them from the log-display when they're not the last line. // In the case of a high-frequency SetTimer, this greatly reduces the log clutter that // would otherwise occur: continue; // Since above didn't continue, this item isn't special, so display it normally. elapsed = sLogTick[line_index + 1 >= LINE_LOG_SIZE ? 0 : line_index + 1] - sLogTick[line_index]; if (elapsed > INT_MAX) // INT_MAX is about one-half of DWORD's capacity. { // v1.0.30.02: Assume that huge values (greater than 24 days or so) were caused by // the new policy of storing WinWait/RunWait/etc.'s line in the buffer whenever // it was interrupted and later resumed by a thread. In other words, there are now // extra lines in the buffer which are considered "special" because they don't indicate // a line that actually executed, but rather one that is still executing (waiting). // See ACT_WINWAIT for details. next_item_is_special = true; // Override the default. if (i + 2 == lines_to_show) // The line after this one is not only special, but the last one that will be shown, so recalculate this one correctly. elapsed = GetTickCount() - sLogTick[line_index]; else // Neither this line nor the special one that follows it is the last. { // Refer to the line after the next (special) line to get this line's correct elapsed time. line_index2 = line_index + 2; if (line_index2 >= LINE_LOG_SIZE) line_index2 -= LINE_LOG_SIZE; elapsed = sLogTick[line_index2] - sLogTick[line_index]; } } } else // This is the last line (whether special or not), so compare it's time against the current time instead. elapsed = GetTickCount() - sLogTick[line_index]; #ifndef AUTOHOTKEYSC // If the this line and the previous line are in different files, display the filename: if (last_file_index != sLog[line_index]->mFileIndex) { last_file_index = sLog[line_index]->mFileIndex; aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("---- %s\r\n"), sSourceFile[last_file_index]); } #endif space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate really huge lines so that the Edit control's size is less likely to be exhausted. // In v1.0.30.02, this is even more likely due to having increased the line-buf's capacity from // 200 to 400, therefore the truncation point was reduced from 500 to 200 to make it more likely // that the first attempt to fit the lines_to_show number of lines into the buffer will succeed. aBuf = sLog[line_index]->ToText(aBuf, space_remaining < 200 ? space_remaining : 200, true, elapsed, this_item_is_special); // If the line above can't fit everything it needs into the remaining space, it will fill all // of the remaining space, and thus the check against LINE_LOG_FINAL_MESSAGE_LENGTH below // should never fail to catch that, and then do a retry. } // Inner for() #define LINE_LOG_FINAL_MESSAGE _T("\r\nPress [F5] to refresh.") // Keep the next line in sync with this. #define LINE_LOG_FINAL_MESSAGE_LENGTH 24 if (BUF_SPACE_REMAINING > LINE_LOG_FINAL_MESSAGE_LENGTH || lines_to_show < 120) // Either success or can't succeed. break; // Otherwise, there is insufficient room to put everything in, but there's still room to retry // with a smaller value of lines_to_show: lines_to_show -= 100; line_index = sLogNext + (LINE_LOG_SIZE - lines_to_show); // Move the starting point forward in time so that the oldest log entries are omitted. } // outer for() that retries the log-to-buffer routine. // Must add the return value, not LINE_LOG_FINAL_MESSAGE_LENGTH, in case insufficient room (i.e. in case // outer loop terminated due to lines_to_show being too small). return aBuf + sntprintf(aBuf, BUF_SPACE_REMAINING, LINE_LOG_FINAL_MESSAGE); } LPTSTR Line::VicinityToText(LPTSTR aBuf, int aBufSize) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 the current line and the lines above and below it into their text equivalent // putting the result into aBuf and returning the position in aBuf of its new string terminator. { LPTSTR aBuf_orig = aBuf; #define LINES_ABOVE_AND_BELOW 7 // Determine the correct value for line_start and line_end: int i; Line *line_start, *line_end; for (i = 0, line_start = this ; i < LINES_ABOVE_AND_BELOW && line_start->mPrevLine != NULL ; ++i, line_start = line_start->mPrevLine); for (i = 0, line_end = this ; i < LINES_ABOVE_AND_BELOW && line_end->mNextLine != NULL ; ++i, line_end = line_end->mNextLine); #ifdef AUTOHOTKEYSC if (!g_AllowMainWindow) // Override the above to show only a single line, to conceal the script's source code. { line_start = this; line_end = this; } #endif // Now line_start and line_end are the first and last lines of the range // we want to convert to text, and they're non-NULL. aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("\tLine#\n")); int space_remaining; // Must be an int to preserve any negative results. // Start at the oldest and continue up through the newest: for (Line *line = line_start;;) { if (line == this) tcslcpy(aBuf, _T("--->\t"), BUF_SPACE_REMAINING); else tcslcpy(aBuf, _T("\t"), BUF_SPACE_REMAINING); aBuf += _tcslen(aBuf); space_remaining = BUF_SPACE_REMAINING; // Resolve macro only once for performance. // Truncate large lines so that the dialog is more readable: aBuf = line->ToText(aBuf, space_remaining < 500 ? space_remaining : 500, false); if (line == line_end) break; line = line->mNextLine; } return aBuf; } LPTSTR Line::ToText(LPTSTR aBuf, int aBufSize, bool aCRLF, DWORD aElapsed, bool aLineWasResumed) // aBufSize should be an int to preserve negatives from caller (caller relies on this). // 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 line into its text equivalent, putting the result into aBuf and // returning the position in aBuf of its new string terminator. { if (aBufSize < 3) return aBuf; else aBufSize -= (1 + aCRLF); // Reserve one char for LF/CRLF after each line (so that it always get added). LPTSTR aBuf_orig = aBuf; aBuf += sntprintf(aBuf, aBufSize, _T("%03u: "), mLineNumber); if (aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("STILL WAITING (%0.2f): "), (float)aElapsed / 1000.0); if (mActionType == ACT_IFBETWEEN || mActionType == ACT_IFNOTBETWEEN) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("if %s %s %s and %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2, RAW_ARG3); else if (ACT_IS_ASSIGN(mActionType) || (ACT_IS_IF(mActionType) && mActionType < ACT_FIRST_COMMAND)) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s%s %s %s") , ACT_IS_IF(mActionType) ? _T("if ") : _T("") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , g_act[mActionType].Name, RAW_ARG2); else if (mActionType == ACT_FOR) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("For %s,%s in %s") , *mArg[0].text ? mArg[0].text : VAR(mArg[0])->mName // i.e. don't resolve dynamic variable names. , *mArg[1].text || !VAR(mArg[1]) ? mArg[1].text : VAR(mArg[1])->mName // can be omitted. , mArg[2].text); else { aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T("%s"), g_act[mActionType].Name); for (int i = 0; i < mArgc; ++i) // This method a little more efficient than using snprintfcat(). // Also, always use the arg's text for input and output args whose variables haven't // been resolved at load-time, since the text has everything in it we want to display // and thus there's no need to "resolve" dynamic variables here (e.g. array%i%). aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(",%s"), (mArg[i].type != ARG_TYPE_NORMAL && !*mArg[i].text) ? VAR(mArg[i])->mName : mArg[i].text); } if (aElapsed && !aLineWasResumed) aBuf += sntprintf(aBuf, BUF_SPACE_REMAINING, _T(" (%0.2f)"), (float)aElapsed / 1000.0); // UPDATE for v1.0.25: It seems that MessageBox(), which is the only way these lines are currently // displayed, prefers \n over \r\n because otherwise, Ctrl-C on the MsgBox copies the lines all // onto one line rather than formatted nicely as separate lines. // Room for LF or CRLF was reserved at the top of this function: if (aCRLF) *aBuf++ = '\r'; *aBuf++ = '\n'; *aBuf = '\0'; return aBuf; } #ifndef MINIDLL void Line::ToggleSuspendState() { // If suspension is being turned on: // It seems unnecessary, and possibly undesirable, to purge any pending hotkey msgs from the msg queue. // Even if there are some, it's possible that they are exempt from suspension so we wouldn't want to // globally purge all messages anyway. g_IsSuspended = !g_IsSuspended; Hotstring::SuspendAll(g_IsSuspended); // Must do this prior to ManifestAllHotkeysHotstringsHooks() to avoid incorrect removal of hook. Hotkey::ManifestAllHotkeysHotstringsHooks(); // Update the state of all hotkeys based on the complex interdependencies hotkeys have with each another. g_script.UpdateTrayIcon(); CheckMenuItem(GetMenu(g_hWnd), ID_FILE_SUSPEND, g_IsSuspended ? MF_CHECKED : MF_UNCHECKED); } #endif void Line::PauseUnderlyingThread(bool aTrueForPauseFalseForUnpause) { if (g <= g_array) // Guard against underflow. This condition can occur when the script thread that called us is the AutoExec section or a callback running in the idle/0 thread. return; if (g[-1].IsPaused == aTrueForPauseFalseForUnpause) // It's already in the right state. return; // Return early because doing the updates further below would be wrong in this case. g[-1].IsPaused = aTrueForPauseFalseForUnpause; // Update the pause state to that specified by caller. if (aTrueForPauseFalseForUnpause) // The underlying thread is being paused when it was unpaused before. ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. else // The underlying thread is being unpaused when it was paused before. --g_nPausedThreads; } ResultType Line::ChangePauseState(ToggleValueType aChangeTo, bool aAlwaysOperateOnUnderlyingThread) // Currently designed to be called only by the Pause command (ACT_PAUSE). // Returns OK or FAIL. { switch (aChangeTo) { case TOGGLED_ON: break; // By breaking instead of returning, pause will be put into effect further below. case TOGGLED_OFF: // v1.0.37.06: The old method was to unpause the the nearest paused thread on the call stack; // but it was flawed because if the thread that made the flag true is interrupted, and the new // thread is paused via the pause command, and that thread is then interrupted, when the paused // thread resumes it would automatically and wrongly be unpaused (i.e. the unpause ticket would // be used at a level higher in the call stack than intended). // Flag this thread so that when it ends, the thread beneath it will be unpaused. If that thread // (which can be the idle thread) isn't paused the following flag-change will be ignored at a later // stage. This method also relies on the fact that the current thread cannot itself be paused right // now because it is what got us here. PauseUnderlyingThread(false); // Necessary even for the "idle thread" (otherwise, the Pause command wouldn't be able to unpause it). return OK; case NEUTRAL: // the user omitted the parameter entirely, which is considered the same as "toggle" case TOGGLE: // Update for v1.0.37.06: "Pause" and "Pause Toggle" are more useful if they always apply to the // thread immediately beneath the current thread rather than "any underlying thread that's paused". if (g > g_array && g[-1].IsPaused) // Checking g>g_array avoids any chance of underflow, which might otherwise happen if this is called by the AutoExec section or a threadless callback running in thread #0. { PauseUnderlyingThread(false); return OK; } //ELSE since the underlying thread is not paused, continue onward to do the "pause enabled" logic below. // (This is the historical behavior because it allows a hotkey like F1::Pause to toggle the script's // pause state on and off -- even though what's really happening involves multiple threads.) break; default: // TOGGLE_INVALID or some other disallowed value. // We know it's a variable because otherwise the loading validation would have caught it earlier: return LineError(ERR_PARAM1_INVALID, FAIL, ARG1); } // Since above didn't return, pause should be turned on. if (aAlwaysOperateOnUnderlyingThread) // v1.0.37.06: Allow underlying thread to be directly paused rather than pausing the current thread. { PauseUnderlyingThread(true); // If the underlying thread is already paused, this flag change will be ignored at a later stage. return OK; } // Otherwise, pause the current subroutine (which by definition isn't paused since it had to be // active to call us). It seems best not to attempt to change the Hotkey mRunAgainAfterFinished // attribute for the current hotkey (assuming it's even a hotkey that got us here) or // for them all. This is because it's conceivable that this Pause command occurred // in a background thread, such as a timed subroutine, in which case we wouldn't want the // pausing of that thread to affect anything else the user might be doing with hotkeys. // UPDATE: The above is flawed because by definition the script's quasi-thread that got // us here is now active. Since it is active, the script will immediately become dormant // when this is executed, waiting for the user to press a hotkey to launch a new // quasi-thread. Thus, it seems best to reset all the mRunAgainAfterFinished flags // in case we are in a hotkey subroutine and in case this hotkey has a buffered repeat-again // action pending, which the user probably wouldn't want to happen after the script is unpaused: #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif return OK; } ResultType Line::ScriptBlockInput(bool aEnable) // Always returns OK for caller convenience. { // Must be running Win98/2000+ for this function to be successful. // We must dynamically load the function to retain compatibility with Win95 (program won't launch // at all otherwise). typedef void (CALLBACK *BlockInput)(BOOL); static BlockInput lpfnDLLProc = (BlockInput)GetProcAddress(GetModuleHandle(_T("user32")), "BlockInput"); // Always turn input ON/OFF even if g_BlockInput says its already in the right state. This is because // BlockInput can be externally and undetectably disabled, e.g. if the user presses Ctrl-Alt-Del: if (lpfnDLLProc) (*lpfnDLLProc)(aEnable ? TRUE : FALSE); g_BlockInput = aEnable; return OK; // By design, it never returns FAIL. } Line *Line::PreparseError(LPTSTR aErrorText, LPTSTR aExtraInfo) // Returns a different type of result for use with the Pre-parsing methods. { // Make all preparsing errors critical because the runtime reliability // of the program relies upon the fact that the aren't any kind of // problems in the script (otherwise, unexpected behavior may result). // Update: It's okay to return FAIL in this case. CRITICAL_ERROR should // be avoided whenever OK and FAIL are sufficient by themselves, because // otherwise, callers can't use the NOT operator to detect if a function // failed (since FAIL is value zero, but CRITICAL_ERROR is non-zero): LineError(aErrorText, FAIL, aExtraInfo); return NULL; // Always return NULL because the callers use it as their return value. } IObject *Line::CreateRuntimeException(LPCTSTR aErrorText, LPCTSTR aWhat, LPCTSTR aExtraInfo) { // Build the parameters for Object::Create() ExprTokenType aParams[5*2]; int aParamCount = 4*2; ExprTokenType* aParam[5*2] = { aParams + 0, aParams + 1, aParams + 2, aParams + 3, aParams + 4
tinku99/ahkdll
a71c463afd2512b3df069e1486d8d011141e4a7a
sandbox mousemove
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2055323 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +AutoHotkey.sdf +AutoHotkey.suo +AutoHotkey.vcxproj.user +ComServer_h.h +ComServer_i.c +Test +bin +ipch +temp diff --git a/source/ComServer.idl b/source/ComServer.idl index 3d2e944..ad4fb2e 100644 --- a/source/ComServer.idl +++ b/source/ComServer.idl @@ -1,73 +1,73 @@ import "wtypes.idl"; [ uuid(A9863C65-8CD4-4069-893D-3B5A3DDFAE88), version(1.0) ] library AutoHotkey { importlib("stdole32.tlb"); #ifdef _WIN64 importlib("stdole2.tlb"); #else importlib("stdole.tlb"); #endif [ uuid(04FFE41B-8FE9-4479-990A-B186EC73F49C), dual, oleautomation ] interface ICOMServer : IDispatch { [id(1)] HRESULT ahktextdll([in,optional] VARIANT script,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] UINT_PTR* hThread); [id(2)] HRESULT ahkdll([in,optional] VARIANT filepath,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] UINT_PTR* hThread); [id(3)] HRESULT ahkPause([in,optional] VARIANT aChangeTo,[out, retval] BOOL* paused); [id(4)] HRESULT ahkReady([out, retval] BOOL* ready); [id(5)] HRESULT ahkFindLabel([in] VARIANT aLabelName,[out, retval] UINT_PTR *pLabel); [id(6)] HRESULT ahkgetvar([in] VARIANT name,[in,optional] VARIANT getVar,[out, retval] VARIANT *returnVal); [id(7)] HRESULT ahkassign([in] VARIANT name,[in,optional] VARIANT value,[out, retval] unsigned int* success); [id(8)] HRESULT ahkExecuteLine([in,optional] VARIANT line,[in,optional] VARIANT aMode,[in,optional] VARIANT wait,[out, retval] UINT_PTR* pLine); [id(9)] HRESULT ahkLabel([in] VARIANT aLabelName,[in,optional] VARIANT nowait,[out, retval] BOOL* success); [id(10)] HRESULT ahkFindFunction([in] VARIANT FuncName,[out, retval] UINT_PTR *pFunc); [id(11)] HRESULT ahkFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] VARIANT* returnVal); [id(12)] HRESULT ahkPostFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] unsigned int* returnVal); [id(13)] HRESULT addScript([in] VARIANT script,[in,optional] VARIANT replace,[out, retval]UINT_PTR* success); [id(14)] HRESULT addFile([in] VARIANT filepath,[in,optional] VARIANT aAllowDuplicateInclude,[in,optional] VARIANT aIgnoreLoadFailure,[out, retval] UINT_PTR* success); [id(15)] HRESULT ahkExec([in] VARIANT script,[out, retval] BOOL* success); [id(16)] HRESULT ahkTerminate([in,optional] VARIANT kill,[out, retval] BOOL* success); } [ uuid(C00BCC8C-5A04-4392-870F-20AAE1B926B2), helpstring("AutoHotkey Script") ] coclass CoCOMServer { [default] interface ICOMServer; } #ifdef _WIN64 [ uuid(38D00012-DC83-4E17-9BAD-D9DD97902580), helpstring("AutoHotkey Script X64") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else #ifdef _UNICODE [ uuid(C58DCD96-1D6F-4F85-B555-02B7F21F5CAF), helpstring("AutoHotkey Script UNICODE") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else - [ uuid(974318D9-A5B2-4FE5-8AC4-33A0C9EBB8B5), - helpstring("AutoHotkey Script ANSI") + [ uuid(CE8DEAC0-C17A-4318-B44F-79D2A4EEF96E), + helpstring("AutoHotkey Script ANSISANDBOX") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #endif //Unicode #endif //Win64 } diff --git a/source/dllmain.cpp b/source/dllmain.cpp index d1478d3..c169e35 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -95,1027 +95,1027 @@ switch(fwdReason) CloseHandle( hThread ); // Unregister window class registered in Script::CreateWindows #ifdef UNICODE UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); #ifndef MINIDLL UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif // MINIDLL #else UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); #ifndef MINIDLL UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif // MINIDLL #endif break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); #ifdef _DEBUG g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA)); #else if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA))) && !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA)))) g_hResource = NULL; #endif InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute"))) { g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0 } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(int timeout) { int lpExitCode = 0; if (hThread == 0) return 0; if (timeout < 1) timeout = 500; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < (timeout/100); i++) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0,0,(timeout/10),0); Sleep((timeout/10)); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else -const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; -const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; -const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; +const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSISANDBOX" ; +const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSISANDBOX" ; +const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSISANDBOX.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false) ; return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; #ifdef DEBUG if (0) // for debugging com #else if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) #endif { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; diff --git a/source/resources/AutoHotkey.rc b/source/resources/AutoHotkey.rc index 4c8d6bb..b241595 100644 --- a/source/resources/AutoHotkey.rc +++ b/source/resources/AutoHotkey.rc @@ -1,241 +1,242 @@ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // //#include "afxres.h" #include <winresrc.h> ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 ///////////////////////////////////////////////////////////////////////////// // // RT_MANIFEST // #ifdef EMBED_MANIFEST // VC++ 2005 and later don't require the next line. CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "AutoHotkey.exe.manifest" #endif // TYPELIB // ReleaseDll must be build before DebugDll to update .tlb file #ifdef _USRDLL #ifdef _WIN64 1 TYPELIB "temp\\x64\\ReleaseDll\\AutoHotkey.tlb" #else #ifdef _UNICODE 1 TYPELIB "temp\\Win32\\ReleaseDll\\AutoHotkey.tlb" #else 1 TYPELIB "temp\\Win32\\ReleaseDll(mbcs)\\AutoHotkey.tlb" #endif #endif #endif #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "//#include ""afxres.h""\r\n" "#include <winresrc.h>\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #ifndef MINIDLL ///////////////////////////////////////////////////////////////////////////// // // Menu // IDR_MENU_MAIN MENU BEGIN POPUP "&File" BEGIN MENUITEM "&Reload Script\tCtrl+R", ID_FILE_RELOADSCRIPT MENUITEM "&Edit Script\tCtrl+E", ID_FILE_EDITSCRIPT MENUITEM "&Window Spy", ID_FILE_WINDOWSPY MENUITEM SEPARATOR MENUITEM "&Pause Script\tPause", ID_FILE_PAUSE MENUITEM "&Suspend Hotkeys", ID_FILE_SUSPEND MENUITEM SEPARATOR MENUITEM "E&xit (Terminate Script)", ID_FILE_EXIT END POPUP "&View" BEGIN MENUITEM "&Lines most recently executed\tCtrl+L", ID_VIEW_LINES MENUITEM "&Variables and their contents\tCtrl+V", ID_VIEW_VARIABLES MENUITEM "&Hotkeys and their methods\tCtrl+H", ID_VIEW_HOTKEYS MENUITEM "&Key history and script info\tCtrl+K", ID_VIEW_KEYHISTORY MENUITEM SEPARATOR MENUITEM "&Refresh\tF5", ID_VIEW_REFRESH END POPUP "&Help" BEGIN MENUITEM "&User Manual\tF1", ID_HELP_USERMANUAL MENUITEM "&Web Site", ID_HELP_WEBSITE END END ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_MAIN ICON "icon_main.ico" IDI_SUSPEND ICON "icon_suspend.ico" IDI_PAUSE ICON "icon_pause.ico" IDI_PAUSE_SUSPEND ICON "icon_pause_suspend.ico" IDI_FILETYPE ICON "icon_filetype.ico" IDI_TRAY_WIN9X ICON "icon_tray_win9x.ico" IDI_TRAY_WIN9X_SUSPEND ICON "icon_tray_win9x_suspend.ico" IDI_TRAY ICON "icon_tray.ico" ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_INPUTBOX DIALOGEX 0, 0, 210, 83 STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME CAPTION "Dialog" FONT 10, "MS Shell Dlg", 400, 0, 0x0 BEGIN EDITTEXT IDC_INPUTEDIT,2,51,207,12,ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,51,67,31,12 PUSHBUTTON "Cancel",IDCANCEL,129,67,31,12 LTEXT "Prompt",IDC_INPUTPROMPT,3,2,205,48 END ///////////////////////////////////////////////////////////////////////////// // // Accelerator // IDR_ACCELERATOR1 ACCELERATORS BEGIN VK_F1, ID_HELP_USERMANUAL, VIRTKEY, NOINVERT "H", ID_VIEW_HOTKEYS, VIRTKEY, CONTROL, NOINVERT "K", ID_VIEW_KEYHISTORY, VIRTKEY, CONTROL, NOINVERT "L", ID_VIEW_LINES, VIRTKEY, CONTROL, NOINVERT VK_F5, ID_VIEW_REFRESH, VIRTKEY, NOINVERT "V", ID_VIEW_VARIABLES, VIRTKEY, CONTROL, NOINVERT VK_PAUSE, ID_FILE_PAUSE, VIRTKEY, NOINVERT "E", ID_FILE_EDITSCRIPT, VIRTKEY, CONTROL, NOINVERT "R", ID_FILE_RELOADSCRIPT, VIRTKEY, CONTROL, NOINVERT END #endif ///////////////////////////////////////////////////////////////////////////// // // Version // #include "..\ahkversion.h" VS_VERSION_INFO VERSIONINFO FILEVERSION AHK_VERSION_N PRODUCTVERSION AHK_VERSION_N FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN #ifdef AUTOHOTKEYSC VALUE "FileDescription", "" VALUE "FileVersion", AHK_VERSION VALUE "InternalName", "" VALUE "LegalCopyright", "" VALUE "OriginalFilename", "" VALUE "ProductName", "" VALUE "ProductVersion", AHK_VERSION #else VALUE "FileDescription", "AutoHotkey_H" VALUE "FileVersion", AHK_VERSION VALUE "InternalName", "AutoHotkey_H" VALUE "LegalCopyright", "Copyright (C) 2010" #ifdef USRDLL #ifdef MINIDLL VALUE "OriginalFilename", "AutoHotkeyMini.dll" #else VALUE "OriginalFilename", "AutoHotkey.dll" #endif #else VALUE "OriginalFilename", "AutoHotkey.exe" #endif VALUE "ProductName", "AutoHotkey_H" VALUE "ProductVersion", AHK_VERSION #endif END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED - +/* // AutoHotkey debugging script #ifdef _DEBUG #ifndef _USRDLL AHK RCDATA "Test\\Test.ahk" #endif -#endif \ No newline at end of file +#endif +*/ \ No newline at end of file diff --git a/source/script.cpp b/source/script.cpp index bbd036a..0826fe1 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -15614,1026 +15614,1026 @@ ResultType Line::PerformLoopReadFile(ExprTokenType *aResultToken, bool &aContinu LoopReadFileStruct loop_info(aReadFile, aWriteFileName); size_t line_length; ResultType result; Line *jump_to_line; global_struct &g = *::g; // Primarily for performance in this case. for (;; ++g.mLoopIteration) { if ( !(line_length = loop_info.mReadFile->ReadLine(loop_info.mCurrentLine, _countof(loop_info.mCurrentLine) - 1)) ) // -1 to ensure there's room for a null-terminator. { // We want to return OK except in some specific cases handled below (see "break"). result = OK; break; } if (loop_info.mCurrentLine[line_length - 1] == '\n') // Remove newlines like FileReadLine does. --line_length; loop_info.mCurrentLine[line_length] = '\0'; g.mLoopReadFile = &loop_info; if (mNextLine->mActionType == ACT_BLOCK_BEGIN) // See PerformLoop() for comments about this section. do result = mNextLine->mNextLine->ExecUntil(UNTIL_BLOCK_END, aResultToken, &jump_to_line); while (jump_to_line == mNextLine); else result = mNextLine->ExecUntil(ONLY_ONE_LINE, aResultToken, &jump_to_line); if (jump_to_line && !(result == LOOP_CONTINUE && jump_to_line == this)) // See comments in PerformLoop() about this section. { if (jump_to_line == this) aContinueMainLoop = true; else aJumpToLine = jump_to_line; // Signal our caller to handle this jump. break; } if (result != OK && result != LOOP_CONTINUE) // i.e. result == LOOP_BREAK || result == EARLY_RETURN || result == EARLY_EXIT || result == FAIL) break; if (aUntil && aUntil->EvaluateLoopUntil(result)) break; } if (loop_info.mWriteFile) { loop_info.mWriteFile->Close(); delete loop_info.mWriteFile; } return result; } __forceinline ResultType Line::Perform() // As of 2/9/2009, __forceinline() reduces code size a little (since this function is called from only one place) and boosts performance a bit, though it's probably more due to the butterfly effect and cache hits/misses. // Performs only this line's action. // Returns OK or FAIL. // The function should not be called to perform any flow-control actions such as // Goto, Gosub, Return, Block-Begin, Block-End, If, Else, etc. { TCHAR buf_temp[MAX_REG_ITEM_SIZE], *contents; // For registry and other things. WinGroup *group; // For the group commands. Var *arg_var2, *output_var = OUTPUT_VAR; // Okay if NULL. Users of it should only consider it valid if their first arg is actually an output_variable. global_struct &g = *::g; // Reduces code size due to replacing so many g-> with g. Eclipsing ::g with local g makes compiler remind/enforce the use of the right one. BOOL arg2_has_binary_integer; ToggleValueType toggle; // For commands that use on/off/neutral. // Use signed values for these in case they're really given an explicit negative value: int start_char_num, chars_to_extract; // For String commands. size_t source_length; // For String commands. SymbolType var_is_pure_numeric, value_is_pure_numeric; // For math operations. vk_type vk; // For GetKeyState. Label *target_label; // For ACT_SETTIMER and ACT_HOTKEY int instance_number; // For sound commands. DWORD component_type; // For sound commands. __int64 device_id; // For sound commands. __int64 helps avoid compiler warning for some conversions. bool is_remote_registry; // For Registry commands. HKEY root_key; // For Registry commands. ResultType result; // General purpose. // Even though the loading-parser already checked, check again, for now, // at least until testing raises confidence. UPDATE: Don't this because // sometimes (e.g. ACT_ASSIGN/ADD/SUB/MULT/DIV) the number of parameters // required at load-time is different from that at runtime, because params // are taken out or added to the param list: //if (nArgs < g_act[mActionType].MinParams) ... switch (mActionType) { case ACT_ASSIGN: // Note: This line's args have not yet been dereferenced in this case (i.e. ExpandArgs() hasn't been // called). The below function will handle that if it is needed. return PerformAssign(); // It will report any errors for us. case ACT_ASSIGNEXPR: // Currently, ACT_ASSIGNEXPR can occur even when mArg[1].is_expression==false, such as things like var:=5 // and var:=Array%i%. Search on "is_expression = " to find such cases in the script-loading/parsing // routines. if (mArgc > 1) { if (mArg[1].is_expression) // v1.0.45: ExpandExpression() already took care of it for us (for performance reasons). return OK; // Above must be checked prior to below since each uses "postfix" in a different way. if (mArg[1].postfix) // There is a cached binary integer. return output_var->Assign(*(__int64 *)mArg[1].postfix); // sArgVar is used to enhance performance, which would otherwise be poor for dynamic variables // such as Var:=Array%i% (which is an expression and handled by ACT_ASSIGNEXPR rather than // ACT_ASSIGN) because Array%i% would have to be resolved twice (once here and once // previously by ExpandArgs()) just to find out if it's IsBinaryClip()). // If ARG2 isn't blank, this ACT_ASSIGNEXPR is assigning an environment variable or g_ErrorLevel // (e.g. var:=Username); so can't apply this optimization. if (ARGVARRAW2 && !*ARG2) // See above. Also, RAW is safe due to the above check of mArgc > 1. { switch(ARGVARRAW2->Type()) { case VAR_NORMAL: // This can be reached via things like: x:=single_naked_var_including_binary_clip // Assign var to var in case ARGVARRAW2->IsBinaryClip(), and for others because // var-to-var has optimizations like retaining the copying over the cached binary number. // In the case of ARGVARRAW2->IsBinaryClip(), performance should be good since // IsBinaryClip() implies a single isolated deref, which would never have been copied // into the deref buffer. // // v1.0.46.01: ARGVARRAW2->IsBinaryClip() can be true because loadtime no longer translates // such statements into ACT_ASSIGN vs. ACT_ASSIGNEXPR. Even without that change, it can also // be reached by something like: // DynClipboardAll = ClipboardAll // ClipSaved := %DynClipboardAll% return output_var->Assign(*ARGVARRAW2); // Var-to-var copy supports ARGVARRAW2 being binary clipboard, and also exploits caching of binary numbers, for performance. case VAR_CLIPBOARDALL: return output_var->AssignClipboardAll(); //Otherwise it's VAR_CLIPBOARD or a read-only variable; continue on to do assign the normal way. } } } // Since above didn't return: // Note that simple assignments such as Var:="xyz" or Var:=Var2 are resolved to be // non-expressions at load-time. In these cases, ARG2 would have been expanded // normally rather than evaluated as an expression. return output_var->Assign(ARG2); // ARG2 now contains the above or the evaluated result of the expression. case ACT_EXPRESSION: // Nothing needs to be done because the expression in ARG1 (which is the only arg) has already // been evaluated and its functions and subfunctions called. Examples: // fn(123, "string", var, fn2(y)) // x&=3 // var ? func() : x:=y return OK; // Like AutoIt2, if either output_var or ARG1 aren't purely numeric, they // will be considered to be zero for all of the below math functions: case ACT_ADD: // Notes about the macro below: // Ordered for short-circuit performance. No need to check if it's g_ErrorLevel (like // ArgMustBeDereferenced() does) because the commands that use it don't internally change ErrorLevel. // RAW is safe because loadtime validation ensured there are at least 2 args. // ACT_ADD/SUB/MULT/DIV are one of the few places that pass true to IsNonBlankIntegerOrFloat(true). // This is for backward compatibility. #define DEFINE_ARG_VAR2 arg_var2 = (ARGVARRAW2 && !*ARG2 && ARGVARRAW2->Type() == VAR_NORMAL) ? ARGVARRAW2 : NULL; #undef DETERMINE_NUMERIC_TYPES #define DETERMINE_NUMERIC_TYPES \ if (arg2_has_binary_integer = mArg[1].postfix && !mArg[1].is_expression)\ {\ value_is_pure_numeric = PURE_INTEGER;\ arg_var2 = NULL;\ }\ else\ {\ DEFINE_ARG_VAR2 \ value_is_pure_numeric = arg_var2 ? arg_var2->IsNonBlankIntegerOrFloat(true)\ : IsPureNumeric(ARG2, true, false, true, true);\ }\ var_is_pure_numeric = output_var->IsNonBlankIntegerOrFloat(true); #undef ARG2_AS_DOUBLE #undef ARG2_AS_INT64 #define ARG2_AS_DOUBLE (arg2_has_binary_integer ? (double)*(__int64*)mArg[1].postfix \ : arg_var2 ? arg_var2->ToDouble(FALSE) : ATOF(ARG2)) #define ARG2_AS_INT64 (arg2_has_binary_integer ? *(__int64*)mArg[1].postfix \ : (arg_var2 ? arg_var2->ToInt64(FALSE) : ATOI64(ARG2))) // Some performance can be gained by relying on the fact that short-circuit boolean // can skip the "var_is_pure_numeric" check whenever value_is_pure_numeric == PURE_FLOAT. // This is because var_is_pure_numeric is never directly needed here (unlike EvaluateCondition()). // However, benchmarks show that this makes such a small difference that it's not worth the // loss of maintainability and the slightly larger code size due to macro expansion: //#undef IF_EITHER_IS_FLOAT //#define IF_EITHER_IS_FLOAT if (value_is_pure_numeric == PURE_FLOAT \ // || IsPureNumeric(output_var->Contents(), true, false, true, true) == PURE_FLOAT) DETERMINE_NUMERIC_TYPES if (!*ARG3 || !_tcschr(_T("SMHD"), ctoupper(*ARG3))) // ARG3 is absent or invalid, so do normal math (not date-time). { IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) + ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) + ARG2_AS_INT64); } // Since above didn't return, the command is being used to add a value to a date-time. if (!value_is_pure_numeric) // It's considered to be zero, so the output_var is left unchanged: return OK; // Since above didn't return: // Use double to support a floating point value for days, hours, minutes, etc: double nUnits; // Declaring separate from initializing avoids compiler warning when not inside a block. nUnits = ARG2_AS_DOUBLE; FILETIME ft, ftNowUTC; if (*output_var->Contents()) { if (!YYYYMMDDToFileTime(output_var->Contents(), ft)) return output_var->Assign(_T("")); // Set to blank to indicate the problem. } else // The output variable is currently blank, so substitute the current time for it. { GetSystemTimeAsFileTime(&ftNowUTC); FileTimeToLocalFileTime(&ftNowUTC, &ft); // Convert UTC to local time. } // Convert to 10ths of a microsecond (the units of the FILETIME struct): switch (ctoupper(*ARG3)) { case 'S': // Seconds nUnits *= (double)10000000; break; case 'M': // Minutes nUnits *= ((double)10000000 * 60); break; case 'H': // Hours nUnits *= ((double)10000000 * 60 * 60); break; case 'D': // Days nUnits *= ((double)10000000 * 60 * 60 * 24); break; } // 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; // Add the specified amount of time to the result value: ul.QuadPart += (__int64)nUnits; // Seems ok to cast/truncate in light of the *=10000000 above. // Convert back into ft struct: ft.dwLowDateTime = ul.LowPart; ft.dwHighDateTime = ul.HighPart; return output_var->Assign(FileTimeToYYYYMMDD(buf_temp, ft, false)); case ACT_SUB: if (!*ARG3 || !_tcschr(_T("SMHD"), ctoupper(*ARG3))) // ARG3 is absent or invalid, so do normal math (not date-time). { DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) - ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) - ARG2_AS_INT64); } // Since above didn't return, the command is being used to subtract date-time values. bool failed; // If either ARG2 or output_var->Contents() is blank, it will default to the current time: __int64 time_until; // Declaring separate from initializing avoids compiler warning when not inside a block. DEFINE_ARG_VAR2 time_until = YYYYMMDDSecondsUntil(arg_var2 ? arg_var2->Contents() : ARG2 , output_var->Contents(), failed); if (failed) // Usually caused by an invalid component in the date-time string. return output_var->Assign(_T("")); switch (ctoupper(*ARG3)) { // Do nothing in the case of 'S' (seconds). Otherwise: case 'M': time_until /= 60; break; // Minutes case 'H': time_until /= 60 * 60; break; // Hours case 'D': time_until /= 60 * 60 * 24; break; // Days } // Only now that any division has been performed (to reduce the magnitude of // time_until) do we cast down into an int, which is the standard size // used for non-float results (the result is always non-float for subtraction // of two date-times): return output_var->Assign(time_until); // Assign as signed 64-bit. case ACT_MULT: DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT return output_var->Assign(output_var->ToDouble(FALSE) * ARG2_AS_DOUBLE); else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. return output_var->Assign(output_var->ToInt64(FALSE) * ARG2_AS_INT64); case ACT_DIV: DETERMINE_NUMERIC_TYPES IF_EITHER_IS_FLOAT { double ARG2_as_float = ARG2_AS_DOUBLE; if (!ARG2_as_float) // v1.0.46: Make behavior more consistent with expressions by return output_var->Assign(); // avoiding a runtime error dialog; just make the output variable blank. return output_var->Assign(output_var->ToDouble(FALSE) / ARG2_as_float); } else // Non-numeric variables or values are considered to be zero for the purpose of the calculation. { __int64 ARG2_as_int = ARG2_AS_INT64; if (!ARG2_as_int) // v1.0.46: Make behavior more consistent with expressions by return output_var->Assign(); // avoiding a runtime error dialog; just make the output variable blank. return output_var->Assign(output_var->ToInt64(FALSE) / ARG2_as_int); } case ACT_STRINGLEFT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) // For these we don't report an error, since it might be intentional for // it to be called this way, in which case it will do nothing other than // set the output var to be blank. chars_to_extract = 0; else { source_length = ArgLength(2); // Should be quick because Arg2 is an InputVar (except when it's a built-in var perhaps). if (chars_to_extract > (int)source_length) chars_to_extract = (int)source_length; // Assign() requires a length that's <= the actual length of the string. } // It will display any error that occurs. return output_var->Assign(ARG2, chars_to_extract); case ACT_STRINGRIGHT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) chars_to_extract = (int)source_length; // It will display any error that occurs: return output_var->Assign(ARG2 + source_length - chars_to_extract, chars_to_extract); case ACT_STRINGMID: // v1.0.43.10: Allow chars-to-extract to be blank, which means "get all characters". // However, for backward compatibility, examine the raw arg, not ARG4. That way, any existing // scripts that use a variable reference or expression that resolves to an empty string will // have the parameter treated as zero (as in previous versions) rather than "all characters". if (mArgc < 4 || !*mArg[3].text) chars_to_extract = INT_MAX; else { chars_to_extract = ArgToInt(4); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 1) return output_var->Assign(); // Set it to be blank in this case. } start_char_num = ArgToInt(3); if (ctoupper(*ARG5) == 'L') // Chars to the left of start_char_num will be extracted. { // TRANSLATE "L" MODE INTO THE EQUIVALENT NORMAL MODE: if (start_char_num < 1) // Starting at a character number that is invalid for L mode. return output_var->Assign(); // Blank seems most appropriate for the L option in this case. start_char_num -= (chars_to_extract - 1); if (start_char_num < 1) // Reduce chars_to_extract to reflect the fact that there aren't enough chars // to the left of start_char_num, so we'll extract only them: chars_to_extract -= (1 - start_char_num); } // ABOVE HAS CONVERTED "L" MODE INTO NORMAL MODE, so "L" no longer needs to be considered below. // UPDATE: The below is also needed for the L option to work correctly. Older: // It's somewhat debatable, but it seems best not to report an error in this and // other cases. The result here is probably enough to speak for itself, for script // debugging purposes: if (start_char_num < 1) start_char_num = 1; // 1 is the position of the first char, unlike StringGetPos. source_length = ArgLength(2); // This call seems unavoidable in both "L" mode and normal mode. if (source_length < (UINT)start_char_num) // Source is empty or start_char_num lies to the right of the entire string. return output_var->Assign(); // No chars exist there, so set it to be blank. source_length -= (start_char_num - 1); // Fix for v1.0.44.14: Adjust source_length to be the length starting at start_char_num. Otherwise, the length passed to Assign() could be too long, and it now expects an accurate length. if ((UINT)chars_to_extract > source_length) chars_to_extract = (int)source_length; return output_var->Assign(ARG2 + start_char_num - 1, chars_to_extract); case ACT_STRINGTRIMLEFT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) // This could be intentional, so don't display an error. chars_to_extract = (int)source_length; return output_var->Assign(ARG2 + chars_to_extract, (VarSizeType)(source_length - chars_to_extract)); case ACT_STRINGTRIMRIGHT: chars_to_extract = ArgToInt(3); // Use 32-bit signed to detect negatives and fit it VarSizeType. if (chars_to_extract < 0) chars_to_extract = 0; source_length = ArgLength(2); if ((UINT)chars_to_extract > source_length) // This could be intentional, so don't display an error. chars_to_extract = (int)source_length; return output_var->Assign(ARG2, (VarSizeType)(source_length - chars_to_extract)); // It already displayed any error. case ACT_STRINGLOWER: case ACT_STRINGUPPER: contents = output_var->Contents(TRUE, TRUE); // Set default. if (contents != ARG2 || output_var->Type() != VAR_NORMAL) // It's compared this way in case ByRef/aliases are involved. This will detect even them. { // Clipboard is involved and/or source != dest. Do it the more comprehensive way. // Set up the var, enlarging it if necessary. If the output_var is of type VAR_CLIPBOARD, // this call will set up the clipboard for writing. // Fix for v1.0.45.02: The v1.0.45 change where the value is assigned directly without sizing the // variable first doesn't work in cases when the variable is the clipboard. This is because the // clipboard's buffer is changeable (for the case conversion later below) only when using the following // approach, not a simple "assign then modify its Contents()". if (output_var->AssignString(NULL, ArgLength(2)) != OK) // The length is in characters, so AssignString(NULL, ...) return FAIL; contents = output_var->Contents(); // Do this only after the above might have changed the contents mem address. // Copy the input variable's text directly into the output variable: _tcscpy(contents, ARG2); } //else input and output are the same, normal variable; so nothing needs to be copied over. Just leave // contents at the default set earlier, then convert its case. if (*ARG3 && ctoupper(*ARG3) == 'T' && !*(ARG3 + 1)) // Convert to title case. StrToTitleCase(contents); else if (mActionType == ACT_STRINGLOWER) CharLower(contents); else CharUpper(contents); return output_var->Close(); // In case it's the clipboard. case ACT_STRINGLEN: return output_var->Assign((__int64)(ARGVARRAW2 && ARGVARRAW2->IsBinaryClip() // Load-time validation has ensured mArgc > 1. ? ARGVARRAW2->Length() // Total size of the binary clip. : ArgLength(2))); // The above must be kept in sync with the StringLen() function elsewhere. case ACT_STRINGGETPOS: { LPTSTR arg4 = ARG4; int pos = -1; // Set default. int occurrence_number; if (*arg4 && _tcschr(_T("LR"), ctoupper(*arg4))) occurrence_number = *(arg4 + 1) ? ATOI(arg4 + 1) : 1; else occurrence_number = 1; // Intentionally allow occurrence_number to resolve to a negative, for scripting flexibility: if (occurrence_number > 0) { if (!*ARG3) // It might be intentional, in obscure cases, to search for the empty string. pos = 0; // Above: empty string is always found immediately (first char from left) regardless // of whether the search will be conducted from the right. This is because it's too // rare to worry about giving it any more explicit handling based on search direction. else { LPTSTR found, haystack = ARG2, needle = ARG3; int offset = ArgToInt(5); // v1.0.30.03 if (offset < 0) offset = 0; size_t haystack_length = ArgLength(2); if (offset < (int)haystack_length) { if (*arg4 == '1' || ctoupper(*arg4) == 'R') // Conduct the search starting at the right side, moving leftward. { // Want it to behave like in this example: If searching for the 2nd occurrence of // FF in the string FFFF, it should find the first two F's, not the middle two: found = tcsrstr(haystack, haystack_length - offset, needle, (StringCaseSenseType)g.StringCaseSense, occurrence_number); } else { // Want it to behave like in this example: If searching for the 2nd occurrence of // FF in the string FFFF, it should find position 3 (the 2nd pair), not position 2: size_t needle_length = ArgLength(3); int i; for (i = 1, found = haystack + offset; ; ++i, found += needle_length) if (!(found = g_tcsstr(found, needle)) || i == occurrence_number) break; } if (found) pos = (int)(found - haystack); // else leave pos set to its default value, -1. } //else offset >= haystack_length, so no match is possible in either left or right mode. } } g_ErrorLevel->Assign(pos < 0 ? ERRORLEVEL_ERROR : ERRORLEVEL_NONE); return output_var->Assign(pos); // Assign() already displayed any error that may have occurred. } case ACT_STRINGREPLACE: return StringReplace(); case ACT_TRANSFORM: return Transform(ARG2, ARG3, ARG4); case ACT_STRINGSPLIT: return StringSplit(ARG1, ARG2, ARG3, ARG4); case ACT_SPLITPATH: return SplitPath(ARG1); case ACT_SORT: return PerformSort(ARG1, ARG2); #ifndef MINIDLL case ACT_PIXELSEARCH: // ArgToInt() works on ARG7 (the color) because any valid BGR or RGB color has 0x00 in the high order byte: return PixelSearch(ArgToInt(3), ArgToInt(4), ArgToInt(5), ArgToInt(6), ArgToInt(7), ArgToInt(8), ARG9, false); case ACT_IMAGESEARCH: return ImageSearch(ArgToInt(3), ArgToInt(4), ArgToInt(5), ArgToInt(6), ARG7); case ACT_PIXELGETCOLOR: return PixelGetColor(ArgToInt(2), ArgToInt(3), ARG4); #endif case ACT_SEND: case ACT_SENDRAW: SendKeys(ARG1, mActionType == ACT_SENDRAW, g.SendMode); return OK; case ACT_SENDINPUT: // Raw mode is supported via {Raw} in ARG1. SendKeys(ARG1, false, g.SendMode == SM_INPUT_FALLBACK_TO_PLAY ? SM_INPUT_FALLBACK_TO_PLAY : SM_INPUT); return OK; case ACT_SENDPLAY: // Raw mode is supported via {Raw} in ARG1. SendKeys(ARG1, false, SM_PLAY); return OK; case ACT_SENDEVENT: SendKeys(ARG1, false, SM_EVENT); return OK; case ACT_CLICK: return PerformClick(ARG1); case ACT_MOUSECLICKDRAG: return PerformMouse(mActionType, SEVEN_ARGS); case ACT_MOUSECLICK: return PerformMouse(mActionType, THREE_ARGS, _T(""), _T(""), ARG5, ARG7, ARG4, ARG6); case ACT_MOUSEMOVE: - return PerformMouse(mActionType, _T(""), ARG1, ARG2, _T(""), _T(""), ARG3, ARG4); - + // return PerformMouse(mActionType, _T(""), ARG1, ARG2, _T(""), _T(""), ARG3, ARG4); + return OK; case ACT_MOUSEGETPOS: return MouseGetPos(ArgToUInt(5)); case ACT_WINACTIVATE: case ACT_WINACTIVATEBOTTOM: if (WinActivate(g, FOUR_ARGS, mActionType == ACT_WINACTIVATEBOTTOM)) // 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; case ACT_WINMINIMIZE: case ACT_WINMAXIMIZE: case ACT_WINRESTORE: case ACT_WINHIDE: case ACT_WINSHOW: case ACT_WINCLOSE: case ACT_WINKILL: { // 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(ARG1, _T("ahk_group"), 9) || *ARG2 || *ARG4); // 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 (mActionType == ACT_WINCLOSE || mActionType == ACT_WINKILL) // ARG3 is contains the wait time. { if (*ARG3 && !(wait_time = (int)(1000 * ArgToDouble(3))) ) wait_time = 500; // Legacy (prior to supporting floating point): 0 is defined as 500ms, which seems more useful than a true zero. if (*ARG5) is_ahk_group = false; // Override the default. } else if (*ARG3) is_ahk_group = false; // Override the default. // Act upon all members of this group (WinText/ExcludeTitle/ExcludeText are ignored in this mode). if (is_ahk_group && (group = g_script.FindGroup(omit_leading_whitespace(ARG1 + 9)))) // Assign. return group->ActUponAll(mActionType, wait_time); // It will do DoWinDelay if appropriate. //else try to act upon it as though "ahk_group something" is a literal window title. // Since above didn't return, it's not "ahk_group", so do the normal single-window behavior. if (mActionType == ACT_WINCLOSE || mActionType == ACT_WINKILL) { if (WinClose(g, ARG1, ARG2, wait_time, ARG4, ARG5, mActionType == ACT_WINKILL)) // It closed something. DoWinDelay; return OK; } else return PerformShowWindow(mActionType, FOUR_ARGS); } case ACT_ENVGET: return EnvGet(ARG2); case ACT_ENVSET: // MSDN: "If [the 2nd] parameter is NULL, the variable is deleted from the current process’s environment." // My: Though it seems okay, for now, just to set it to be blank if the user omitted the 2nd param or // left it blank (AutoIt3 does this too). Also, no checking is currently done to ensure that ARG2 // isn't longer than 32K, since future OSes may support longer env. vars. SetEnvironmentVariable() // might return 0(fail) in that case anyway. Also, ARG1 may be a dereferenced variable that resolves // to the name of an Env. Variable. In any case, this name need not correspond to any existing // variable name within the script (i.e. script variables and env. variables aren't tied to each other // in any way). This seems to be the most flexible approach, but are there any shortcomings? // The only one I can think of is that if the script tries to fetch the value of an env. var (perhaps // one that some other spawned program changed), and that var's name corresponds to the name of a // script var, the script var's value (if non-blank) will be fetched instead. // Note: It seems, at least under WinXP, that env variable names can contain spaces. So it's best // not to validate ARG1 the same way we validate script variables (i.e. just let\ // SetEnvironmentVariable()'s return value determine whether there's an error). However, I just // realized that it's impossible to "retrieve" the value of an env var that has spaces (until now, // since the EnvGet command is available). return SetErrorLevelOrThrowBool(!SetEnvironmentVariable(ARG1, ARG2)); case ACT_ENVUPDATE: { // From the AutoIt3 source: // AutoIt3 uses SMTO_BLOCK (which prevents our thread from doing anything during the call) // vs. SMTO_NORMAL. Since I'm not sure why, I'm leaving it that way for now: ULONG_PTR nResult; return SetErrorLevelOrThrowBool(!SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)_T("Environment"), SMTO_BLOCK, 15000, &nResult)); } case ACT_URLDOWNLOADTOFILE: return URLDownloadToFile(TWO_ARGS); case ACT_RUNAS: if (!g_os.IsWin2000orLater()) // Do nothing if the OS doesn't support it. return OK; StringTCharToWChar(ARG1, g_script.mRunAsUser); StringTCharToWChar(ARG2, g_script.mRunAsPass); StringTCharToWChar(ARG3, g_script.mRunAsDomain); return OK; case ACT_RUN: { bool use_el = tcscasestr(ARG3, _T("UseErrorLevel")); result = g_script.ActionExec(ARG1, NULL, ARG2, !use_el, ARG3, NULL, use_el, true, ARGVAR4); // Be sure to pass NULL for 2nd param. if (use_el) // The special string ERROR is used, rather than a number like 1, because currently // RunWait might in the future be able to return any value, including 259 (STATUS_PENDING). result = g_ErrorLevel->Assign(result ? ERRORLEVEL_NONE : _T("ERROR")); // Otherwise, if result == FAIL, above already displayed the error (or threw an exception). return result; } case ACT_RUNWAIT: case ACT_CLIPWAIT: case ACT_KEYWAIT: case ACT_WINWAIT: case ACT_WINWAITCLOSE: case ACT_WINWAITACTIVE: case ACT_WINWAITNOTACTIVE: return PerformWait(); case ACT_WINMOVE: return mArgc > 2 ? WinMove(EIGHT_ARGS) : WinMove(_T(""), _T(""), ARG1, ARG2); case ACT_WINMENUSELECTITEM: return WinMenuSelectItem(ELEVEN_ARGS); case ACT_CONTROLSEND: case ACT_CONTROLSENDRAW: return ControlSend(SIX_ARGS, mActionType == ACT_CONTROLSENDRAW); case ACT_CONTROLCLICK: if ( !(vk = ConvertMouseButton(ARG4)) ) // Treats blank as "Left". return LineError(ERR_PARAM4_INVALID, FAIL, ARG4); return ControlClick(vk, *ARG5 ? ArgToInt(5) : 1, ARG6, ARG1, ARG2, ARG3, ARG7, ARG8); case ACT_CONTROLMOVE: return ControlMove(NINE_ARGS); case ACT_CONTROLGETPOS: return ControlGetPos(ARG5, ARG6, ARG7, ARG8, ARG9); case ACT_CONTROLGETFOCUS: return ControlGetFocus(ARG2, ARG3, ARG4, ARG5); case ACT_CONTROLFOCUS: return ControlFocus(FIVE_ARGS); case ACT_CONTROLSETTEXT: return ControlSetText(SIX_ARGS); case ACT_CONTROLGETTEXT: return ControlGetText(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_CONTROL: return Control(SEVEN_ARGS); case ACT_CONTROLGET: return ControlGet(ARG2, ARG3, ARG4, ARG5, ARG6, ARG7, ARG8); case ACT_STATUSBARGETTEXT: return StatusBarGetText(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_STATUSBARWAIT: return StatusBarWait(EIGHT_ARGS); case ACT_POSTMESSAGE: case ACT_SENDMESSAGE: return ScriptPostSendMessage(mActionType == ACT_SENDMESSAGE); case ACT_PROCESS: return ScriptProcess(THREE_ARGS); case ACT_WINSET: return WinSet(SIX_ARGS); case ACT_WINSETTITLE: return mArgc > 1 ? WinSetTitle(FIVE_ARGS) : WinSetTitle(_T(""), _T(""), ARG1); case ACT_WINGETTITLE: return WinGetTitle(ARG2, ARG3, ARG4, ARG5); case ACT_WINGETCLASS: return WinGetClass(ARG2, ARG3, ARG4, ARG5); case ACT_WINGET: return WinGet(ARG2, ARG3, ARG4, ARG5, ARG6); case ACT_WINGETTEXT: return WinGetText(ARG2, ARG3, ARG4, ARG5); case ACT_WINGETPOS: return WinGetPos(ARG5, ARG6, ARG7, ARG8); case ACT_SYSGET: return SysGet(ARG2, ARG3); case ACT_WINMINIMIZEALL: PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 419, 0); DoWinDelay; return OK; case ACT_WINMINIMIZEALLUNDO: PostMessage(FindWindow(_T("Shell_TrayWnd"), NULL), WM_COMMAND, 416, 0); DoWinDelay; return OK; case ACT_ONEXIT: if (!*ARG1) // Reset to normal Exit behavior. { g_script.mOnExitLabel = NULL; return OK; } // If it wasn't resolved at load-time, it must be a variable reference: if ( !(target_label = (Label *)mAttribute) ) if ( !(target_label = g_script.FindLabel(ARG1)) ) return LineError(ERR_NO_LABEL, FAIL, ARG1); g_script.mOnExitLabel = target_label; return OK; #ifndef MINIDLL case ACT_HOTKEY: // mAttribute is the label resolved at loadtime, if available (for performance). return Hotkey::Dynamic(THREE_ARGS, (Label *)mAttribute); #endif case ACT_SETTIMER: // A timer is being created, changed, or enabled/disabled. // Note that only one timer per label is allowed because the label is the unique identifier // that allows us to figure out whether to "update or create" when searching the list of timers. if ( !(target_label = (Label *)mAttribute) ) // Since it wasn't resolved at load-time, it must be a variable reference. if ( !(target_label = (*ARG1 ? g_script.FindLabel(ARG1) : g.CurrentLabel)) ) return LineError(ERR_NO_LABEL, FAIL, ARG1); // And don't update mAttribute (leave it NULL) because we want ARG1 to be dynamically resolved // every time the command is executed (in case the contents of the referenced variable change). // In the data structure that holds the timers, we store the target label rather than the target // line so that a label can be registered independently as a timers even if there another label // that points to the same line such as in this example: // Label1:: // Label2:: // ... // return if (*ARG2) { toggle = Line::ConvertOnOff(ARG2); if (!toggle && !IsPureNumeric(ARG2, true, true, true)) // Allow it to be neg. or floating point at runtime. return LineError(ERR_PARAM2_INVALID, FAIL, ARG2); } else toggle = TOGGLE_INVALID; // Below relies on distinguishing a true empty string from one that is sent to the function // as empty as a signal. Don't change it without a full understanding because it's likely // to break compatibility or something else: switch(toggle) { case TOGGLED_ON: case TOGGLED_OFF: g_script.UpdateOrCreateTimer(target_label, _T(""), ARG3, toggle == TOGGLED_ON, false); break; // Timer is always (re)enabled when ARG2 specifies a numeric period or is blank + there's no ARG3. // If ARG2 is blank but ARG3 (priority) isn't, tell it to update only the priority and nothing else: default: g_script.UpdateOrCreateTimer(target_label, ARG2, ARG3, true, !*ARG2 && *ARG3); } return OK; case ACT_CRITICAL: { // v1.0.46: When the current thread is critical, have the script check messages less often to // reduce situations where an OnMesage or GUI message must be discarded due to "thread already // running". Using 16 rather than the default of 5 solves reliability problems in a custom-menu-draw // script and probably many similar scripts -- even when the system is under load (though 16 might not // be enough during an extreme load depending on the exact preemption/timeslice dynamics involved). // DON'T GO TOO HIGH because this setting reduces response time for ALL messages, even those that // don't launch script threads (especially painting/drawing and other screen-update events). // Future enhancement: Could allow the value of 16 to be customized via something like "Critical 25". // However, it seems best not to allow it to go too high (say, no more than 2000) because that would // cause the script to completely hang if the critical thread never finishes, or takes a long time // to finish. A configurable limit might also allow things to work better on Win9x because it has // a bigger tickcount granularity. // Some hardware has a tickcount granularity of 15 instead of 10, so this covers more variations. DWORD peek_frequency_when_critical_is_on = 16; // Set default. See below. // v1.0.48: Below supports "Critical 0" as meaning "Off" to improve compatibility with A_IsCritical. // In fact, for performance, only the following are no recognized as turning on Critical: // - "On" // - "" // - Integer other than 0. // Everything else, if considered to be "Off", including "Off", "Any non-blank string that // doesn't start with a non-zero number", and zero itself. g.ThreadIsCritical = !*ARG1 // i.e. a first arg that's omitted or blank is the same as "ON". See comments above. || !_tcsicmp(ARG1, _T("ON")) || (peek_frequency_when_critical_is_on = ArgToUInt(1)); // Non-zero integer also turns it on. Relies on short-circuit boolean order. if (g.ThreadIsCritical) // Critical has been turned on. (For simplicity even if it was already on, the following is done.) { g.PeekFrequency = peek_frequency_when_critical_is_on; g.AllowThreadToBeInterrupted = false; g.LinesPerCycle = -1; // v1.0.47: It seems best to ensure SetBatchLines -1 is in effect because g.IntervalBeforeRest = -1; // otherwise it may check messages during the interval that it isn't supposed to. } else // Critical has been turned off. { // Since Critical is being turned off, allow thread to be immediately interrupted regardless of // any "Thread Interrupt" settings. g.PeekFrequency = DEFAULT_PEEK_FREQUENCY; g.AllowThreadToBeInterrupted = true; } // Once ACT_CRITICAL returns, the thread's interruptibility has been explicitly set; so the script // is now in charge of managing this thread's interruptibility. return OK; } case ACT_THREAD: switch (ConvertThreadCommand(ARG1)) { case THREAD_CMD_PRIORITY: g.Priority = ArgToInt(2); break; case THREAD_CMD_INTERRUPT: // If either one is blank, leave that setting as it was before. if (*ARG1) g_script.mUninterruptibleTime = ArgToInt(2); // 32-bit (for compatibility with DWORDs returned by GetTickCount). if (*ARG2) g_script.mUninterruptedLineCountMax = ArgToInt(3); // 32-bit also, to help performance (since huge values seem unnecessary). break; case THREAD_CMD_NOTIMERS: g.AllowTimers = (*ARG2 && ArgToInt64(2) == 0); break; // If invalid command, do nothing since that is always caught at load-time unless the command // is in a variable reference (very rare in this case). } return OK; case ACT_GROUPADD: // Adding a WindowSpec *to* a group, not adding a group. { if ( !(group = (WinGroup *)mAttribute) ) if ( !(group = g_script.FindGroup(ARG1, true)) ) // Last parameter -> create-if-not-found. return FAIL; // It already displayed the error for us. target_label = NULL; if (*ARG4) { if ( !(target_label = (Label *)mRelatedLine) ) // Jump target hasn't been resolved yet, probably due to it being a deref. if ( !(target_label = g_script.FindLabel(ARG4)) ) return LineError(ERR_NO_LABEL, FAIL, ARG4); // Can't do this because the current line won't be the launching point for the // Gosub. Instead, the launching point will be the GroupActivate rather than the // GroupAdd, so it will be checked by the GroupActivate or not at all (since it's // not that important in the case of a Gosub -- it's mostly for Goto's): //return IsJumpValid(label->mJumpToLine); group->mJumpToLabel = target_label; } return group->AddWindow(ARG2, ARG3, ARG5, ARG6); } // Note ACT_GROUPACTIVATE is handled by ExecUntil(), since it's better suited to do the Gosub. case ACT_GROUPDEACTIVATE: if ( !(group = (WinGroup *)mAttribute) ) group = g_script.FindGroup(ARG1); if (group) group->Deactivate(*ARG2 && !_tcsicmp(ARG2, _T("R"))); // Note: It will take care of DoWinDelay if needed. //else nonexistent group: By design, do nothing. return OK; case ACT_GROUPCLOSE: if ( !(group = (WinGroup *)mAttribute) ) group = g_script.FindGroup(ARG1); if (group) if (*ARG2 && !_tcsicmp(ARG2, _T("A"))) group->ActUponAll(ACT_WINCLOSE, 0); // Note: It will take care of DoWinDelay if needed. else group->CloseAndGoToNext(*ARG2 && !_tcsicmp(ARG2, _T("R"))); // Note: It will take care of DoWinDelay if needed. //else nonexistent group: By design, do nothing. return OK; case ACT_GETKEYSTATE: return GetKeyJoyState(ARG2, ARG3); case ACT_RANDOM: { if (!output_var) // v1.0.42.03: Special mode to change the seed. { init_genrand(ArgToUInt(2)); // It's documented that an unsigned 32-bit number is required. return OK; } bool use_float = IsPureNumeric(ARG2, true, false, true) == PURE_FLOAT || IsPureNumeric(ARG3, true, false, true) == PURE_FLOAT; if (use_float) { double rand_min = *ARG2 ? ArgToDouble(2) : 0; double rand_max = *ARG3 ? ArgToDouble(3) : INT_MAX; // Seems best not to use ErrorLevel for this command at all, since silly cases // such as Max > Min are too rare. Swap the two values instead. if (rand_min > rand_max) { double rand_swap = rand_min; rand_min = rand_max; rand_max = rand_swap; } return output_var->Assign((genrand_real1() * (rand_max - rand_min)) + rand_min); } else // Avoid using floating point, where possible, which may improve speed a lot more than expected. { int rand_min = *ARG2 ? ArgToInt(2) : 0; int rand_max = *ARG3 ? ArgToInt(3) : INT_MAX; // Seems best not to use ErrorLevel for this command at all, since silly cases // such as Max > Min are too rare. Swap the two values instead. if (rand_min > rand_max) { int rand_swap = rand_min; rand_min = rand_max; rand_max = rand_swap; } // Do NOT use genrand_real1() 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: // AutoIt3: __int64 is needed here to do the proper conversion from unsigned long to signed long: return output_var->Assign( (int)(__int64(genrand_int32() % ((__int64)rand_max - rand_min + 1)) + rand_min) ); } } case ACT_DRIVESPACEFREE: return DriveSpace(ARG2, true); case ACT_DRIVE: return Drive(THREE_ARGS); case ACT_DRIVEGET: return DriveGet(ARG2, ARG3); case ACT_SOUNDGET: case ACT_SOUNDSET: device_id = *ARG4 ? ArgToInt(4) - 1 : 0; if (device_id < 0) device_id = 0; instance_number = 1; // Set default. component_type = *ARG2 ? SoundConvertComponentType(ARG2, &instance_number) : MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; return SoundSetGet(mActionType == ACT_SOUNDGET ? NULL : ARG1 , component_type, instance_number // Which instance of this component, 1 = first , *ARG3 ? SoundConvertControlType(ARG3) : MIXERCONTROL_CONTROLTYPE_VOLUME // Default , (UINT)device_id); case ACT_SOUNDGETWAVEVOLUME: case ACT_SOUNDSETWAVEVOLUME: device_id = *ARG2 ? ArgToInt(2) - 1 : 0; if (device_id < 0) device_id = 0; return (mActionType == ACT_SOUNDGETWAVEVOLUME) ? SoundGetWaveVolume((HWAVEOUT)device_id) : SoundSetWaveVolume(ARG1, (HWAVEOUT)device_id); case ACT_SOUNDBEEP: // For simplicity and support for future/greater capabilities, no range checking is done. // It simply calls the function with the two DWORD values provided. It avoids setting // ErrorLevel because failure is rare and also because a script might want play a beep // right before displaying an error dialog that uses the previous value of ErrorLevel. Beep(*ARG1 ? ArgToUInt(1) : 523, *ARG2 ? ArgToUInt(2) : 150); return OK; case ACT_SOUNDPLAY: return SoundPlay(ARG1, *ARG2 && !_tcsicmp(ARG2, _T("wait")) || !_tcsicmp(ARG2, _T("1"))); case ACT_FILEAPPEND: // Uses the read-file loop's current item filename was explicitly leave blank (i.e. not just // a reference to a variable that's blank): return FileAppend(ARG2, ARG1, (mArgc < 2) ? g.mLoopReadFile : NULL); case ACT_FILEREAD: return FileRead(ARG2); case ACT_FILEREADLINE: return FileReadLine(ARG2, ARG3); case ACT_FILEDELETE: return FileDelete(); case ACT_FILERECYCLE: return FileRecycle(ARG1); case ACT_FILERECYCLEEMPTY: return FileRecycleEmpty(ARG1); #ifndef MINIDLL case ACT_FILEINSTALL: return FileInstall(THREE_ARGS); #endif case ACT_FILECOPY: { int error_count = Util_CopyFile(ARG1, ARG2, ArgToInt(3) == 1, false, g.LastError); if (!error_count) return g_ErrorLevel->Assign(ERRORLEVEL_NONE); if (g_script.mIsAutoIt2) return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // For backward compatibility with v2. return SetErrorLevelOrThrowInt(error_count); } case ACT_FILEMOVE: return SetErrorLevelOrThrowInt(Util_CopyFile(ARG1, ARG2, ArgToInt(3) == 1, true, g.LastError)); case ACT_FILECOPYDIR: return SetErrorLevelOrThrowBool(!Util_CopyDir(ARG1, ARG2, ArgToInt(3) == 1)); case ACT_FILEMOVEDIR: if (ctoupper(*ARG3) == '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 SetErrorLevelOrThrowBool(!MoveFile(ARG1, ARG2)); } // Otherwise: return SetErrorLevelOrThrowBool(!Util_MoveDir(ARG1, ARG2, ArgToInt(3))); case ACT_FILECREATEDIR: return FileCreateDir(ARG1); case ACT_FILEREMOVEDIR: return SetErrorLevelOrThrowBool(!*ARG1 // Consider an attempt to create or remove a blank dir to be an error. || !Util_RemoveDir(ARG1, ArgToInt(2) == 1)); // Relies on short-circuit evaluation. case ACT_FILEGETATTRIB: // The specified ARG, if non-blank, takes precedence over the file-loop's file (if any): #define USE_FILE_LOOP_FILE_IF_ARG_BLANK(arg) (*arg ? arg : (g.mLoopFile ? g.mLoopFile->cFileName : _T(""))) return FileGetAttrib(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); case ACT_FILESETATTRIB: FileSetAttrib(ARG1, USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), ConvertLoopMode(ARG3), ArgToInt(4) == 1); return !g.ThrownToken ? OK : FAIL; case ACT_FILEGETTIME: return FileGetTime(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), *ARG3); case ACT_FILESETTIME: FileSetTime(ARG1, USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), *ARG3, ConvertLoopMode(ARG4), ArgToInt(5) == 1); return !g.ThrownToken ? OK : FAIL; case ACT_FILEGETSIZE: return FileGetSize(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2), ARG3); case ACT_FILEGETVERSION: return FileGetVersion(USE_FILE_LOOP_FILE_IF_ARG_BLANK(ARG2)); case ACT_SETWORKINGDIR:
tinku99/ahkdll
294c5254dd55a0965e00462a2695c177d40dd598
Upload AhkDll help (generated with GenDocs v2)
diff --git a/AhkDll_GenDocs.ahk b/AhkDll_GenDocs.ahk new file mode 100644 index 0000000..c32e109 --- /dev/null +++ b/AhkDll_GenDocs.ahk @@ -0,0 +1,615 @@ +;: Title: AhkDll by tinku99 powered by HotKeyIt +; + +; Function: AutoHotkey.dll +; Description: +; AutoHotkey.dll was invented by <a href=http://www.autohotkey.com/forum/profile.php?mode=viewprofile&u=6056>tinku99</a> and enhanced by <a href=http://www.autohotkey.com/forum/profile.php?mode=viewprofile&u=9238>HotKeyIt</a>, it is a custom build of <a href=http://www.autohotkey.com/forum/viewtopic.php?p=210161#210161>AutoHotkey_L</a> (by <a href=http://www.autohotkey.com/forum/profile.php?mode=viewprofile&u=3754>Lexikos</a>).<br>AutoHotkey.dll can be used in other programming languages and allows multithreading in AutoHotkey.<br><b><a href=http://www.autohotkey.net/~HotKeyIt/AutoHotkey.zip>GET AutoHotkey V1 PACKAGE HERE.</a><br><a href=http://www.autohotkey.net/~HotKeyIt/AutoHotkey2Alpha.zip>GET AutoHotkey V2alpha PACKAGE HERE.</a></b> +; Syntax: DllCall(dll_path "\" "function","UInt/Str/...",...,"Cdecl ...") +; Parameters: +; Get started - To use AutoHotkey.dll you need AutoHotkey.exe or anther program able to load and run a dll or use COM.<br>In AutoHotkey.exe, AutoHotkey.dll is loaded using <b>DllCall("LoadLibrary","Str","dllpath or name")</b>, you can also use AutoHotkey.dll COM Interface.<br>Other languages and programs that support loading dlls have similar functions. (<a href=http://www.autohotkey.com/forum/viewtopic.php?t=61457>python</a>, <a href=http://www.autohotkey.com/forum/viewtopic.php?p=339622#339622>c#/c++</a>)<br><br>Each loaded AutoHotkey.dll will serve an additional thread with full AutoHotkey functionality.<br><br>To unload AutoHotkey.dll you can use DllCall("FreeLibrary","UInt",handleLibrary).<br>To start the actual thrad you will need to use ahkdll or ahktextdll (exported functions). Click the link below to read more about ahkdll and ahktextdll. +; Why AutoHotkey.dll - <b>Multithreading</b><br>We can run multiple threads simultaneously by loading several dlls. For example you can use Input command to catch user input and perform your task in background so no Input gets lost and your code works uninterupted.<br>It is even possible to use same variables and objects using Alias() function, but be careful, when variable gets reallocated because its memory increases and you are accessing it, your program might crash, therefore you can use <a href=http://www.autohotkey.com/forum/topic51335.html>CriticalSection()</a> to avoid simultaneous access.<br><br> +; AutoHotkey.dll <b>Exported Functions</b> - ahkdll = start new thread from ahk file. <b>(not available in AutoHotkey.exe)</b><br>ahktextdll = start new thread from string that contains an ahk script. <b>(not available in AutoHotkey.exe)</b><br>ahkReady = check if a script is running.<br>addFile = add new script(lines) to existing(running) script from a file.<br>addScript = add new script(lines) from string that contains an ahk script.<br>ahkExec = execute a script from a string that contains ahk script.<br>ahkLabel = jump(GoTo/GoSub) to a label.<br>ahkFunction = Call a function and return result.<br>ahkPostFunction = call function without getting result and continuing with script immediately.<br>ahkassign = assign new value to a variable<br>ahkgetvar = get value of a variable<br>ahkTerminate = terminate the script/thread <b>(not available in AutoHotkey.exe)</b><br>ahkReload = reload script<br>ahkFindFunc = find a function and return a handle to it.<br>ahkFindLabel = find a label and return a handle to it.<br>ahkPause = pause the script.<br>ahkExecuteLine = Execute script from certain line or get first/next line.<br><br> +; AutoHotkey.dll <b>COM interface</b> - AutoHotkey.dll includes a COM Interface so you can use AutoHotkey trough COM, see examples below.<br>Following interfaces are available:<br>AutoHotkey V1:<br> - AutoHotkey.Script = last registered (Unicode/Ansi/X64)<br> - AutoHotkey.Script.UNICODE = unicode win32<br> - AutoHotkey.Script.ANSI = ansi win32<br> - AutoHotkey.Script.X64 = unicode x64<br>AutoHotkey V2:<br> - AutoHotkey2.Script = last registered (Unicode/X64)<br> - AutoHotkey2.Script.UNICODE = unicode win32<br> - AutoHotkey2.Script.X64 = unicode x64 +; Return Value: +; See function help. +; Remarks: +; None. +; Related: +; Example: +; file:Example_General.ahk +; + +; +; Function: ahkdll +; Description: +; ahkdll is used to launch a file containing AutoHotkey script in a separate thread using AutoHotkey.dll. ( Available in AutoHotkey[Mini].dll only, not in AutoHotkey_H.exe) +; Syntax: hThread:=DllCall(dll_path "\<b>ahkdll</b>","Str","MyScript.ahk","Str",options,"Str",parameters,"Cdecl UPTR") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; hThread - ahkdll() returns a thread handle. +; "MyScript.ahk" - This parameter must be an existing ahk file. +; options - Within the script you can access this parameter via build in variable A_ScriptOptions. +; (parameters) - Parameters passed to dll. Similar to <b>Run myscript.exe "parameters"<b> +; Return Value: +; <b>Cdecl UPTR</b> - ahkdll returns a thread handle, using this handle you can use functions like DllCall("SuspendThread/ResumeThread/GetExitCode",...)... for your thread. +; Remarks: +; Don't forget to load AutoHotkey.dll via DllCall("LoadLibrary"...), otherwise it will be automatically Freed by AutoHotkey.exe after DllCall finished. +; Related: +; Example: +; file:Example_ahkdll.ahk +; + +; +; Function: ahktextdll +; Description: +; ahktextdll is used to launch a script in a separate thread using AutoHotkey.dll from text/variable. ( Available in AutoHotkey[Mini].dll only, not in AutoHotkey_H.exe) +; Syntax: hThread:=DllCall(dll_path "\<b>ahktextdll</b>","Str","MsgBox % dll_path`nMsgBox % A_Now`nReturn","Str",options,"Str",parameters,"Cdecl UPTR") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; hThread - ahktextdll() returns a thread handle. +; ("MsgBox...") - This parameter must be an AutoHotkey script as text or variable containing a script as text. +; (options) - Within the script you can access this parameter via build in variable A_ScriptOptions. +; (parameters) - Parameters passed to dll. Similar to <b>Run myscript.exe "parameters"<b> +; Return Value: +; <b>Cdecl UPTR</b> - ahkdll returns a thread handle, using this handle you can use functions like DllCall("SuspendThread/ResumeThread/GetExitCode",...)... for your thread. +; Remarks: +; Don't forget to load AutoHotkey.dll via DllCall("LoadLibrary"...), otherwise it will be automatically Freed by AutoHotkey.exe after DllCall finished. +; Related: +; Example: +; file:Example_ahktextdll.ahk +; + +; +; Function: ahkReady +; Description: +; ahkReady is used to check if a dll script is running or not. ( Available in AutoHotkey[Mini].dll only, not in AutoHotkey_H.exe) +; Syntax: ThreadIsRunning:=DllCall(dll_path "\<b>ahkReady</b>") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; ThreadIsRunning - ahkReady() returns 1 if a thread is running or 0 otherwise. +; Return Value: +; 1 or 0. +; Remarks: +; None. +; Related: +; Example: +; file:Example_ahkReady.ahk +; + +; +; Function: addFile +; Description: +; addFile is used to append additional labels and functions from a file to the running script. +; Syntax: pointerLine:=DllCall(dll_path "\<b>addFile</b>","Str",file[,"Uchar",AllowDuplicateInclude,"Uchar",IgnoreLoadFailure],"Cdecl UPTR") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; pointerLine - addFile() returns a pointer to the first line in the late included script. +; file - name of script to be parsed and added to the running script +; AllowDuplicateInclude - 0 = if a script named %filename% is already loaded, ignore (do not load)<br>1 = load it again +; IgnoreLoadFailure - 0 = signal an error if there was problem addfileing filename<br>1 = ignore error<br>2 = remove script lines added by previous calls to addFile() and start executing at the first line in the new script [AutoHotkey.dll only] +; Return Value: +; <b>Cdecl UInt</b> - return value is a pointer to the first line of new created lines. +; Remarks: +; Line pointer can be used in ahkExecuteLine() to execute one line only or until a return is encountered. +; Related: +; Example: +; file:Example_addFile.ahk +; + +; +; Function: addScript +; Description: +; addScript is used to append additional labels and functions from text or variable to the running script from text/variable. +; Syntax: pointerLine:=DllCall(dll_path "\<b>addScript</b>","Str","MsgBox % A_Now"[,"Uchar",Execute,],"Cdecl UPTR") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; pointerLine - addScript() returns a pointer to the first line in the late included script. +; ("MsgBox...") - script as text(or variable containing text) added to the running script. +; Execute - 0 = add only but do not execute.<br>1 = add script and start execution.<br>2 = add script and wait until executed +; Return Value: +; <b>Cdecl UInt</b> - return value is a pointer to the first line of new created lines. +; Remarks: +; Line pointer can be used in ahkExecuteLine() to execute one line only or until a return is encountered. +; Related: +; Example: +; file:Example_addScript.ahk +; + +; +; Function: ahkExec +; Description: +; ahkExec is used to run some code from text/variable temporarily. +; Syntax: success:=DllCall(dll_path "\<b>ahkExec</b>","Str","MsgBox % A_Now") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; success - ahkExec() returns true if script was executed and false if not +; ("MsgBox...") - script as text(or variable containing text) that will be executed. +; Return Value: +; Returns true if script was executed and false if there was an error. +; Remarks: +; None. +; Related: +; Example: +; file:Example_ahkExec.ahk +; + +; +; Function: ahkLabel +; Description: +; ahkLabel is used to launch a Goto/GoSub routine in script. +; Syntax: labelFound:=DllCall(dll_path "\<b>ahkLabel</b>","Str","MyLabel","UInt",nowait,"Cdecl UInt") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; labelFound - ahkLabel() returns 1 if label exists else 0. +; label ("MyLabel") - name of label to launch. +; nowait - 0 = Gosub (default), 1 = GoTo (PostMessage mode) +; Return Value: +; <b>Cdecl UInt</b> - returns 1 if label exists else 0. +; Remarks: +; Default is 0 = wait for code to finish execution, this is because PostMessage is not reliable and might be scipped so script will not execute. +; Related: +; Example: +; file:Example_ahkLabel.ahk +; + +; +; Function: ahkFunction +; Description: +; ahkFunction is used to launch a function in script. +; Syntax: ReturnValue:=DllCall(dll_path "\<b>ahkFunction</b>","Str","MyFunction",["Str",param1,"Str",param2,...,param10],"Cdecl Str") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; ReturnValue - ahkFunction returns the value that is returned by the launched function as string/text. +; param1 to param10 - Parameters to pass to the function. These parameters are optional. +; Return Value: +; <b>Cdecl Str</b> - return value is always a string/text, add 0 to make sure it resolves to number if necessary. +; Remarks: +; None. +; Related: +; Example: +; file:Example_ahkFunction.ahk +; + +; +; Function: ahkPostFunction +; Description: +; ahkPostFunction is used to launch a function in script and return <b>immediately</b> (so function will run in background and return value will be ignored). +; Syntax: ReturnValue:=DllCall(dll_path "\<b>ahkPostFunction</b>","Str","MyFunction",["Str",param1,"Str",param2,...,param10],"Cdecl UInt") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; ReturnValue - ahkPostFunction returns 1 if function exists else 0. +; param1 to param10 - Parameters to pass to the function. These parameters are optional. +; Return Value: +; <b>Cdecl UInt</b> - return returns 0 if function exists else -1. +; Remarks: +; None. +; Related: +; Example: +; file:Example_ahkPostFunction.ahk +; + +; +; Function: ahkassign +; Description: +; ahkassign is used to assign a string to a variable in script. +; Syntax: Success:=DllCall(dll_path "\<b>ahkassign</b>","Str","variable","Str",value) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; ReturnValue - returns 0 on success and -1 on failure. +; variable - name of variable to save value in. +; value - value to be saved in variable, can be sting/text only. +; Return Value: +; Return value is 0 on success and -1 on failure. +; Remarks: +; ahkassign will create the variable if it does not exist. +; Related: +; Example: +; file:Example_ahkassign.ahk +; + +; +; Function: ahkgetvar +; Description: +; ahkgetvar is used to get a value from a variable in script. +; Syntax: Value:=DllCall(dll_path "\<b>ahkgetvar</b>","Str","var","UInt",getPointer,"Cdecl Str") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; Value - ahkgetvar() returns the value of a variable as string. +; var - name of variable to get value from. +; getPointer - set to 1 to get pointer of variable to use with Alias(), else 0 to get the value. +; Return Value: +; <b>Cdecl Str</b> - return value is always a string, add 0 to convert to integer if necessary, especially when using getPointer. +; Remarks: +; ahkgetvar returns empty if variable does not exist or is empty. +; Related: +; Example: +; file:Example_ahkgetvar.ahk +; + +; +; Function: ahkTerminate +; Description: +; ahkTerminate is used to stop and exit a running script in dll. ( Available in AutoHotkey[Mini].dll only, not in AutoHotkey_H.exe) +; Syntax: DllCall(dll_path "\<b>ahkTerminate</b>","Int",timeout,"Cdecl Int") +; Parameters: +; timeout - Time in miliseconds to wait until thread exits.<br>If this parameter is 0 it defaults to 500. +; Return Value: +; Returns always 0. +; Remarks: +; ahkTerminate will destroy script hotkeys and hotstrings and exit the thread. ahkTerminate uses SendMessageTimeout for better reliability. +; Related: +; Example: +; file:Example_ahkTerminate.ahk +; + +; +; Function: ahkReload +; Description: +; ahkReload is used to stop and exit a running script in dll. ( Available in AutoHotkey[Mini].dll only, not in AutoHotkey_H.exe ) +; Syntax: DllCall(dll_path "\<b>ahkReload</b>") +; Parameters: +; No parameters - No parameters +; Return Value: +; Returns always 0 for success. +; Remarks: +; ahkReload will destroy hotkeys and hotstrings, exit thread and start it again using same parameters/file/text. +; Related: +; Example: +; file:Example_ahkReload.ahk +; + +; +; Function: ahkFindFunc +; Description: +; ahkFundFunc is used to get function its pointer. (Equivalent to FindFunc) +; Syntax: DllCall(dll_path "\<b>ahkFindFunc</b>","Str","func","Cdecl PTR") +; Parameters: +; func - Name of function. +; Return Value: +; <b>Cdecl UPTR</b> - Function pointer. +; Remarks: +; None +; Related: +; Example: +; file:Example_ahkFindFunc.ahk +; + +; +; Function: ahkFindLabel +; Description: +; ahkFundLabel is used to get a pointer to the label. (Equivalent to FindLabel) +; Syntax: DllCall(dll_path "\<b>ahkFindLabel</b>","Str","label","Cdecl UPTR") +; Parameters: +; label - Name of label. +; Return Value: +; <b>Cdecl UPTR</b> - Label pointer. +; Remarks: +; None +; Related: +; Example: +; file:Example_ahkFindLabel.ahk +; + +; +; Function: ahkPause +; Description: +; ahkPause is used to pause a thread and run traditional AutoHotkey Sleep, so it is different to DllCall("SuspendThread",...), so thread remains active and you can still do various things with it like ahkgetvar. +; Syntax: DllCall(dll_path "\<b>ahkPause</b>"[,"Str","on"]) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; State - On or 1 to enable Pause / Off or 0 to disable pause. Pass empty string to find out whether thread is paused. +; Return Value: +; <b>Cdecl Int</b> - return 1 if thread is paused or 0 if it is not. +; Remarks: +; None. +; Related: +; Example: +; file:Example_ahkPause.ahk +; + +; +; Function: ahkExecuteLine +; Description: +; ahkExecuteLine is used to execute the script from previously added line via addScript or addFile. +; Syntax: pointerNextLine := DllCall(dll_path "\<b>ahkExecuteLine</b>"[,"UPTR",pointerLine,"UInt",mode,"Uint",wait],"Cdecl UPTR") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; pointerNextLine - a pointer to next line. When no line pointer is passed, it returns a pointer to FirstLine. +; pointerLine - a pointer to the line to be executed. +; mode - 0 = will not execute but return a pointer to next line.<br>1 = UNTIL_RETURN<br>2 = UNTIL_BLOCK_END<br>3 = ONLY_ONE_LINE +; wait - set 1 to wait until the execution finished (be careful as it may happen that the dll call never return! +; Return Value: +; <b>Cdecl UInt</b> - if no pointerLine is passed it returns a pointer to FirstLine, else it returns a pointer to NextLine. +; Remarks: +; addFile and addScript return a line pointer, so you can add one or more lines of script and launch them without having a Label to it.<br><b>A_LineFile<b/> contains the full file path of currently running script (ahkdll + addFile) or the script in text form (ahktextdll or addScript).<br>Functions are skipped so you recive the pointer to line after function. +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: Alias +; Description: +; Build in function Alias is used to convert a variable into a pointer to another variable. +; Syntax: Alias(alias, alias_for) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; alias - A reference to a local variable or function parameter. +; alias_for - A reference to or the address of a user-defined variable. +; Return Value: +; Not used. +; Remarks: +; An alias is akin to a ByRef function parameter. However, an optional ByRef parameter is not an alias when it is omitted from a function call. +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: cacheEnable +; Description: +; Build in function to re-enable binary number caching for a variable. +; Syntax: cacheEnable(var)<br>cacheEnable(%varContainingNameOfVar%) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; var - An unquoted variable reference. +; Return Value: +; Not used. +; Remarks: +; In AutoHotkey v1.0.48, binary numbers are cached in variables to avoid conversions to/from strings. However, taking the address of a variable (e.g. &var) marks that variable as uncacheable because it allows the user to read/write its contents in unconventional ways. This function may be used to re-enable binary number caching however, any address previously taken may become invalid or out-of-sync with the actual contents of the variable.<br><br>If var is a ByRef parameter, caching is re-enabled for the underlying variable. +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: FindFunc +; Description: +; Build in function to retrieve a pointer to the Func structure of a function with the given name. +; Syntax: func_ptr := FindFunc(FuncName) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; FuncName - The name of a user-defined or built-in function. +; Return Value: +; Pointer to a function. +; Remarks: +; None +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: FindLabel +; Description: +; Build in function to retrieve a pointer to structure of a label. +; Syntax: label_ptr := FindLabel(LabelName) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; LabelName - The name of an existing label. +; Return Value: +; Pointer to a label. +; Remarks: +; None +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: getTokenValue +; Description: +; Build in function to retrieve a value from an ExprTokenType structure. +; Syntax: value := getTokenValue(pointer-expression)<br>value := getTokenValue(varContainingPointer+0) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; pointer-expression - An expression which results in a pointer to an ExprTokenType structure. This must not be a variable reference, string, floating-point number or numeric literal. +; Return Value: +; Value from an ExprTokenType structure. +; Remarks: +; None +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: getVar +; Description: +; Build in function to get a pointer to the Var structure of a user-defined variable. +; Syntax: var_ptr := getVar(var)<br>var_ptr := getVar(%varContainingNameOfVar%) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; var - A reference to a user-defined variable. +; Return Value: +; Value from an ExprTokenType structure. +; Remarks: +; None +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: Static +; Description: +; Build in function to make a variable static. +; Syntax: static(var)<br>static(%varContainingNameOfVar%) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; var - A reference to a local variable or non-ByRef parameter. +; Return Value: +; Value from an ExprTokenType structure. +; Remarks: +; None +; Related: +; Example: +; file: AhkDll_Example.ahk +; + +; +; Function: AutoHotkeyMini +; Description: +; AutoHotkeyMini.dll excludes many commands to support much faster load/reload and less memory consumption. +; Syntax: Useful when a program uses many threads. +; Parameters: +; Disabled commands - Hotkey (as well as Hotkey + Hotstring functionality), Gui…, GuiControl[Get], Menu..., TrayIcon, FileInstall, ListVars, ListLines, ListHotkeys, KeyHistory, SplashImage, SplashText..., Progress, PixelSearch, PixelGetColor, InputBox, FileSelect and FolderSelect dialogs, Input, BlockInput MouseMove[Off], Build in variables related to Hotkeys and Icons as well as Gui, A_ThisHotkey..., A_IsSuspended, A_Icon.... +; Return Value: +; None. +; Remarks: +; None. +; Related: +; Example: +; file: No_Example.ahk +; + +; +; Function: DynaCall +; Description: +; Build in function, similar to DllCall but works with DllCall structures and Object syntax.<br>It is faster than DllCall, easier to use and saves a lot of typing and code. +; Syntax: objfunc:=DynaCall(FilePath . "\function",[parameter_definition,default_param1,default_param2,...])<br><br>objfunc.[DllCallReturnType](params...) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; function - Can be a function address, name of function or path\name for the function.<br>E.g. "GetProcAddress" or "kernel32\LoadLibrary" +; parameter_definition - Int = i / Str = s / AStr = a / WStr = w / Short = h / Char = c / Float = f / Double = d / Ptr = t / Int64 = 6 <br>U prefix and * or p is supported as well, for example: "ui=ui*s"<br>You can change order of parameters using an object declaration.<br>For example: DynaCall("SendMessage",["t=tuitt",3,2],hwnd,WM_ACTIVATE:=0x06)<br>So when calling the function first parameter is wParam and second Msg. See example below. +; default_param - You can set the parameters already when a Token is created, that way you can call the function without passing parameters as these are alredy set. When default_value is not given, parameters will default to 0 or "".<br>CDecl calling convention can be changed using ==, for example "t==ui". +; DllCall_Return_Type - Optional. Using this you can override default return type previously defined in parameter_definition.<br>Use same return types as in DllCall (Int/Str/AStr/WStr/Short/Char/Float/Double/Ptr/Int64). +; How to call the function - Any Object syntax can be used to call the function. For example:<br><br>objfunc[params...]<br>objfunc.param<br>objfunc.(params...) ; NOTE it is not objfunc(params...)<br>objfunc.param1 := param2<br>objfunc.Str(params...) ; here we can use a different return type than defined in defnition. +; Return Value: +; objfunc will contain the DynaToken object that can be used to call the dll function using any object syntax. +; Remarks: +; DynaCall uses same ErrorLevel as DllCall.<br>DynaCall can be also used to call the function, therefore pass a DynaToken that was created via DynaCall previously, followed by parameters. E.g. DynaCall(objfunc,parameters...). +; Related: +; Example: +; file:Example_DynaCall.ahk +; + +; +; Function: CriticalSection +; Description: +; Build in functions, to Lock and Unlock a CriticalSection. +; Syntax: Lock(&CriticalSeciton) / TryLock(&CriticalSeciton) / UnLock(&CriticalSeciton) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; &CriticalSection - Pointer to a critical section, see: <a href=http://www.autohotkey.com/forum/viewtopic.php?t=51335>CriticalSection</href>. +; Return Value: +; None. +; Remarks: +; These functions are build in because they are faster than user defined functions. CriticalSection function can be found <a href=http://www.autohotkey.com/forum/topic51335.html>here</a>. +; Related: +; Example: +; file: No_Example.ahk +; + + +; +; Function: CriticalObject +; Description: +; Build in function to make an object multi-thread safe. +; Syntax: CriticalObject := CriticalObject([obj,lpCriticalSection]) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; obj - Can be an object or an object reference, when omitted an empty object will be created.<br>To find out the pointer of referenced object or Critical Section this must be a CriticalObject, see example. +; lpCriticalSection - a pointer to Critical Section, when omitted AutoHotkey will create internal Critical Section and use it.<br>When obj is a CriticalObject this can be 1 to get pointer to referenced object or 2 to get pointer to Critical Section. +; Return Value: +; Returns a Critical Object. This object uses Critical Section internally to disallow simultanous access while in script it can be used as a normal object +; Remarks: +; Note, when CriticalObject is deleted, its CrticalSection is not deleted, if needed delete it manually before deleting last reference to CriticalObject.<br>Note, you cannot use ObjRelease(CriticalObject) because it will not give you the referenced object but the criticalObject. +; Related: +; Example: +; file:Example_CriticalObject.ahk +; + + +; +; Function: MemoryLoadLibrary +; Description: +; Build in function to load a dll multiple times from Memory.<br>Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html +; Syntax: hLibrary:=MemoryLoadLibrary(FilePath) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; FilePath - A path to a file on disk that will be loaded into memory and LoadLibrary from there. +; Return Value: +; Returns handle of Library. +; Remarks: +; This handle can be used to get process address of exported functions for this dll (MemoryGetProcAddress). +; Related: +; Example: +; file:Example_MemoryLibrary.ahk +; + +; +; Function: ResourceLoadLibrary +; Description: +; Build in function to load a dll multiple times from Resource. (For compiled scripts only) <br>Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html +; Syntax: hLibrary:=ResourceLoadLibrary(FilePath) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; FilePath - A path to a file that was included via FileInstall,FilePath,.... +; Return Value: +; Returns handle of Library. +; Remarks: +; This handle can be used to get process address of exported functions for this dll (MemoryGetProcAddress). +; Related: +; Example: +; file:Example_ResourceLibrary.ahk +; + +; +; Function: MemoryGetProcAddress +; Description: +; Build in function to get a pointer to exported functions of a dll to use in DllCall().<br>Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html +; Syntax: pFunc:=MemoryGetProcAddress(hLibrary,"function") +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; hLibrary - The handle returned by MemoryLoadLibrary(). +; function - Function to get the pointer for. +; Return Value: +; Returns a pointer to the function that can be used in DllCall(). +; Remarks: +; You can access these functions only by using pointer in DllCall! +; Related: +; Example: +; file:Example_MemoryLibrary.ahk +; + +; +; Function: MemoryFreeLibrary +; Description: +; Build in function to free the Library loaded from Memory by MemoryLoadLibrary.<br>Based on http://www.joachim-bauch.de/tutorials/load_dll_memory.html +; Syntax: MemoryFreeLibrary(hLibrary) +; Parameters: +; <b>Parameter</b> - <b>Description</b> +; hLibrary - The handle returned by MemoryLoadLibrary(). +; Return Value: +; This function does not return a value. +; Remarks: +; None. +; Related: +; Example: +; file:Example_MemoryLibrary.ahk +; + +; +; Function: Other Changes +; Description: +; Differences to AutoHotkey_L.exe and other changes. +; Syntax: General Changes +; Parameters: +; <b>Change</b> - <b>Info</b> +; #NoEnv - this is now default, use #NoEnv, Off to enable use of Environment variables. +; Sleep in Send - Send {100}a{100}b including integer higher than 9 in brackets will do a sleep between sending keystrokes +; SendMode Input - this is now default SendMode, use SendMode,... to change. +; A_DllPath - Build in variable that contains the path of running dll. +; StdLib - additionally Lib.lnk (a link to library folder) can be present in AutoHotkey.exe directory. +; Input - added support for Multithreading.<br>Added A option to append input to the variable (so variable will not be set empty before input starts) +; Compile exe or dll - in AutoHotkey_H any bin/exe/dll can be compiled. Modified Ahk2Exe can be found here: https://github.com/HotKeyIt/Ahk2Exe +; /E switch - Compiled exe and dll can stil execute scripts.<br>Run myexe.exe /E myscript.ahk<br>dll.ahkdll("myscript.ahk","","/E")<br>dll.ahktextdll("MsgBox","","/E") +; Return Value: +; None. +; Remarks: +; None. +; Related: +; Example: +; file:Example_Input.ahk +; \ No newline at end of file
tinku99/ahkdll
fd85a6b0ce7d543e9f61a1b0f8f60e3c7dae1865
Fixed COM ahkFunction and ahkPostFunction
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 2e375fa..e0bf00f 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -553,602 +553,602 @@ EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false) ; return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::ahkKey(/*[in]*/ VARIANT name,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkKey(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) ,Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; #ifdef DEBUG - if (0 && GetModuleFileName(g_hInstance, buf, MAX_PATH)) // for debugging com + if (0) // for debugging com #else if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) #endif { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; } // // Server unregistration // STDAPI DllUnregisterServer() { HRESULT hr = UnregisterServer(CLSID_CoCOMServerOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr = UnregisterServer(CLSID_CoCOMServer, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { UnRegisterTypeLib( g_hInstance, NULL); } return hr; } #endif #endif \ No newline at end of file diff --git a/source/exports.cpp b/source/exports.cpp index ef611f4..71a8e22 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -105,649 +105,649 @@ EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } -void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); +void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar = true); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. - AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 - if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 + AssignVariant(*aFunc->mParam[0].var, param1); // Assign parameter #1 + if (aFunc->mParamCount > 1 && param2.vt != VT_ERROR) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. - AssignVariant(*aFunc->mParam[1].var, param2, false); - if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 + AssignVariant(*aFunc->mParam[1].var, param2); + if (aFunc->mParamCount > 2 && param3.vt != VT_ERROR) // Assign parameter #3 { - AssignVariant(*aFunc->mParam[2].var, param3, false); - if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 + AssignVariant(*aFunc->mParam[2].var, param3); + if (aFunc->mParamCount > 3 && param4.vt != VT_ERROR) // Assign parameter #4 { - AssignVariant(*aFunc->mParam[3].var, param4, false); - if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 + AssignVariant(*aFunc->mParam[3].var, param4); + if (aFunc->mParamCount > 4 && param5.vt != VT_ERROR) // Assign parameter #5 { - AssignVariant(*aFunc->mParam[4].var, param5, false); - if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 + AssignVariant(*aFunc->mParam[4].var, param5); + if (aFunc->mParamCount > 5 && param6.vt != VT_ERROR) // Assign parameter #6 { - AssignVariant(*aFunc->mParam[5].var, param6, false); - if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 + AssignVariant(*aFunc->mParam[5].var, param6); + if (aFunc->mParamCount > 6 && param7.vt != VT_ERROR) // Assign parameter #7 { - AssignVariant(*aFunc->mParam[6].var, param7, false); - if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 + AssignVariant(*aFunc->mParam[6].var, param7); + if (aFunc->mParamCount > 7 && param8.vt != VT_ERROR) // Assign parameter #8 { - AssignVariant(*aFunc->mParam[7].var, param8, false); - if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 + AssignVariant(*aFunc->mParam[7].var, param8); + if (aFunc->mParamCount > 8 && param9.vt != VT_ERROR) // Assign parameter #9 { - AssignVariant(*aFunc->mParam[8].var, param9, false); - if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 + AssignVariant(*aFunc->mParam[8].var, param9); + if (aFunc->mParamCount > 9 && param10.vt != VT_ERROR) // Assign parameter #10 { - AssignVariant(*aFunc->mParam[9].var, param10, false); + AssignVariant(*aFunc->mParam[9].var, param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; }
tinku99/ahkdll
f4e7c151b7a8de2f15daecfe929f7184e8f87a06
Fixed COM string conversation
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 67818fc..2e375fa 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -215,924 +215,940 @@ int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCm } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(int timeout) { int lpExitCode = 0; if (hThread == 0) return 0; if (timeout < 1) timeout = 500; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < (timeout/100); i++) { SendMessageTimeout(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0,0,(timeout/10),0); Sleep((timeout/10)); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : aDefaultDllScript, argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { + USES_CONVERSION; if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *paused = com_ahkPause(Variant2T(aChangeTo,buf)); + *paused = com_ahkPause(aChangeTo.vt == VT_BSTR ? OLE2T(aChangeTo.bstrVal) : Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { + USES_CONVERSION; if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *aLabelPointer = com_ahkFindLabel(Variant2T(aLabelName,buf)); + *aLabelPointer = com_ahkFindLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { + USES_CONVERSION; if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; - var = g_script.FindVar(Variant2T(name,buf)) ; + var = g_script.FindVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; - if ( !(var = g_script.FindOrAddVar(Variant2T(name,namebuf))) ) + if ( !(var = g_script.FindOrAddVar(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false) ; return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ UINT_PTR* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *success = com_ahkLabel(Variant2T(aLabelName,buf),Variant2I(nowait)); + *success = com_ahkLabel(aLabelName.vt == VT_BSTR ? OLE2T(aLabelName.bstrVal) : Variant2T(aLabelName,buf) + ,Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ UINT_PTR* pFunc) { + USES_CONVERSION; if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *pFunc = com_ahkFindFunc(Variant2T(FuncName,buf)); + *pFunc = com_ahkFindFunc(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { + USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; - b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); + b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) + , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { + USES_CONVERSION; if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; - b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); + b = ahkFunctionVariant(FuncName.vt == VT_BSTR ? OLE2T(FuncName.bstrVal) : Variant2T(FuncName,buf) + , param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::ahkKey(/*[in]*/ VARIANT name,/*[out, retval]*/ BOOL* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *success = com_ahkKey(Variant2T(name,buf)); + *success = com_ahkKey(name.vt == VT_BSTR ? OLE2T(name.bstrVal) : Variant2T(name,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ UINT_PTR* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *success = com_addScript(Variant2T(script,buf),Variant2I(replace)); + *success = com_addScript(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ UINT_PTR* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *success = com_addFile(Variant2T(filepath,buf),Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); + *success = com_addFile(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf) + ,Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { + USES_CONVERSION; if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; - *success = com_ahkExec(Variant2T(script,buf)); + *success = com_ahkExec(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; #ifdef DEBUG if (0 && GetModuleFileName(g_hInstance, buf, MAX_PATH)) // for debugging com #else if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) #endif { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; } // // Server unregistration // STDAPI DllUnregisterServer() { HRESULT hr = UnregisterServer(CLSID_CoCOMServerOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_AutoHotkey) ; hr = UnregisterServer(CLSID_CoCOMServer, g_szVerIndProgID, g_szProgID, LIBID_AutoHotkey) ; if (SUCCEEDED(hr)) { UnRegisterTypeLib( g_hInstance, NULL); } return hr; } #endif #endif \ No newline at end of file
tinku99/ahkdll
f9ca1fbc91fb5227d0bc065a011d43d33eee1018
Fixed Dynacall Cdecl declaration and allow different return type
diff --git a/source/script2.cpp b/source/script2.cpp index 8317813..f3e463f 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -12374,1334 +12374,1334 @@ DYNARESULT DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD & return Res; } void ConvertDllArgType(LPTSTR aBuf[], DYNAPARM &aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[32]; int i; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf[0]; i < 2 && type_string; type_string = aBuf[++i]) { 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) { // The following also serves to set the default in case this is the first iteration. // Set default but perform second iteration in case the second type string isn't NULL. // In other words, if the second type string is explicitly valid rather than blank, // it should override the following default: aDynaParam.type = DLL_ARG_INVALID; // To assist with detection of errors like DllCall(...,flaot,n), treat empty string as an error; naked "CDecl" is now handled elsewhere. OBSOLETE COMMENT: Assume int. This is relied upon at least for having a return type such as a naked "CDecl". continue; // OK to do this regardless of whether this is the first or second iteration. } tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below. // v1.0.30.02: The addition of 'P' allows the quotes to be omitted around a pointer type. // However, the current detection below relies upon the fact that not 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; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsicmp(buf, _T(t))) aDynaParam.type = (n); TEST_TYPE("Int", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("Str", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("Ptr", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("Ptr", DLL_ARG_INT) #endif TEST_TYPE("Short", DLL_ARG_SHORT) TEST_TYPE("Char", DLL_ARG_CHAR) TEST_TYPE("Int64", DLL_ARG_INT64) TEST_TYPE("Float", DLL_ARG_FLOAT) TEST_TYPE("Double", DLL_ARG_DOUBLE) TEST_TYPE("AStr", DLL_ARG_ASTR) TEST_TYPE("WStr", DLL_ARG_WSTR) TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. { if (i > 0) // Second iteration. { // Reset flags to go with any blank value (i.e. !*buf) we're falling back to from the first iteration // (in case our iteration changed the flags based on bogus contents of the second type_string): aDynaParam.passed_by_address = false; aDynaParam.is_unsigned = false; //aDynaParam.type: The first iteration already set it to DLL_ARG_INT or DLL_ARG_INVALID. } else // First iteration, so aDynaParam.type's value will be set by the second (however, the loop's own condition will skip the second iteration if the second type_string is NULL). { aDynaParam.type = DLL_ARG_INVALID; // Set in case of: 1) the second iteration is skipped by the loop's own condition (since the caller doesn't always initialize "type"); or 2) the second iteration can't find a valid type. continue; } } // Since above didn't "continue", the type is explicitly valid so "return" to ensure that // the second iteration doesn't run (in case this is the first iteration): return; } } int ConvertDllArgTypes(LPTSTR aBuf, DYNAPARM *aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[1024]; int i; int arg_count = 0; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf; *type_string; type_string = (aBuf + (++i))) { if (_tcschr(type_string,'=') || ctoupper(*type_string) == 'U' || (*type_string == '*') )// Unsigned continue; if (i>0 && ctoupper(*(aBuf + i - 1)) == 'U') // Unsigned aDynaParam[arg_count].is_unsigned = true; else aDynaParam[arg_count].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) break; tcslcpy(buf, type_string+1, 2); // Make a modifiable copy for easier parsing below. if (StrChrAny(buf, _T("*pP"))) // Additional validation: ensure nothing following the suffix. aDynaParam[arg_count].passed_by_address = true; else aDynaParam[arg_count].passed_by_address = false; tcslcpy(buf, type_string, 2); // Make a modifiable copy for easier parsing below. if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(buf, _T(t), 1)) aDynaParam[arg_count].type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. break; arg_count++; } return arg_count; } bool IsDllArgTypeName(LPTSTR name) // Test whether given name is a valid DllCall arg type (used by Script::MaybeWarnLocalSameAsGlobal). { LPTSTR names[] = { name, NULL }; DYNAPARM param; // An alternate method using an array of strings and tcslicmp in a loop benchmarked // slightly faster than this, but didn't seem worth the extra code size. This should // be more maintainable and is guaranteed to be consistent with what DllCall accepts. ConvertDllArgType(names, param); return param.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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } void BIF_CriticalObject(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj = (CriticalObject*)TokenToObject(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } IObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else obj->AddRef(); } // create new critical object and save reference CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { // Check if we own the critical section and release it if (TryEnterCriticalSection(this->lpCriticalSection)) { LeaveCriticalSection(this->lpCriticalSection); } return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed while (!TryEnterCriticalSection(this->lpCriticalSection)) MsgSleep(-1); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } void BIF_DynaCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParam[0]->symbol == SYM_OBJECT) { aParam[0]->object->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); } else if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // IObject *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } else if (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject()) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } ExprTokenType token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string[1]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE,TRUE); } else { return_type_string[0] = token.marker; } int i = 0; for (;return_type_string[0][i];i++) { if ( !(_tcschr(return_type_string[0]+i,'=') || ctoupper(return_type_string[0][i]) == 'U' || ctoupper(return_type_string[0][i]) == 'P' || (return_type_string[0][i] == '*')) )// Unsigned obj->marg_count++; } DYNAPARM *dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string[0],dyna_param)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string[0],'=')) { #ifdef WIN32_PLATFORM - obj->mdll_call_mode = DC_CALL_CDECL; + if (_tcschr((_tcschr(return_type_string[0],'=') + 1),'=')) + obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR retrurn_type_arg[3]; // maximal length of return type for (i=0;_tcschr(return_type_string[0] + i + 1,'=');i++) retrurn_type_arg[i] = return_type_string[0][i]; retrurn_type_arg[i] = '\0'; if (StrChrAny(retrurn_type_arg, _T("uU"))) { _tcsncpy(retrurn_type_arg,retrurn_type_arg + 1,sizeof(TCHAR)); _tcsncpy(retrurn_type_arg + 1,retrurn_type_arg + 2,sizeof(TCHAR)); //*(retrurn_type_arg + 2) = '\0'; obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(retrurn_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(retrurn_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE - else - { - g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. - return NULL; - } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); if (!obj->mfunction) { g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } // allocate memory for parameters and default parameters // in current design we need to have mdefault_param to be initialized // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before passing a buffer 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 (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters IObject *paramobj = ((aParam[1]->symbol == SYM_OBJECT) ? aParam[1]->object : aParam[1]->var->mObject); oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); paramobj->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. if (result_token.value_int64 < 2) { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } else { obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; paramobj->Invoke(result_token,*aParam[1],IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } else { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; + if (is_call && aParam[0]->symbol == SYM_OPERAND && _tcscmp(aParam[0]->marker,_T(""))) + { + ConvertDllArgType(&aParam[0]->marker, return_attrib); + } for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) { this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; continue; } ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = is_call; i < aParamCount; ++arg_count, i += 1) // Same loop as used in above, so maintain them together. { ExprTokenType &this_param = *aParam[i]; // Resolved for performance and convenience. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[arg_count+1] : arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } return OK; } void BIF_DllCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Stores a number or a SYM_STRING result in aResultToken. // Sets ErrorLevel to the error code appropriate to any problem that occurred. // 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) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); HMODULE hmodule_to_free = NULL; // Set default in case of early goto; mostly for maintainability. void *function; // Will hold the address of the function to be called. // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch(aParam[0]->symbol) { case SYM_STRING: // By far the most common, so it's listed first for performance. Also for performance, don't even consider the possibility that a quoted literal string like "33" is a function-address. function = NULL; // Indicate that no function has been specified yet. break; case SYM_VAR: // 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 = (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) ? (void *)aParam[0]->var->ToInt64(TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. // 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 ErrorLevel of 0xc0000005. //if (temp64 <= 0) //{ // g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. // return; //} //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; if (IS_NUMERIC(token.symbol) || token.symbol == SYM_OBJECT) // The return type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } LPTSTR return_type_string[2]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. } else { return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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.
tinku99/ahkdll
1f9637415d917bcd7b01b6ffe05c98a237279070
Fixed MemoryModule not to search for manifest if there are no resources
diff --git a/source/MemoryModule.cpp b/source/MemoryModule.cpp index 5b5159d..b65d152 100644 --- a/source/MemoryModule.cpp +++ b/source/MemoryModule.cpp @@ -1,596 +1,597 @@ /* * Memory DLL loading code * Version 0.0.2 * * Copyright (c) 2004-2011 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2011 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif #include <Windows.h> #include <winnt.h> #include <stdio.h> //#ifdef DEBUG_OUTPUT //#include <stdio.h> //#endif #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif #include "MemoryModule.h" typedef struct { PIMAGE_NT_HEADERS headers; unsigned char *codeBase; HMODULE *modules; int numModules; int initialized; } MEMORYMODULE, *PMEMORYMODULE; typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen((const char*)tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugStringA(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); #ifdef _WIN64 section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; #else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; #endif } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_EXECUTE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_READWRITE}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) { #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page"); #endif break; } } } #ifndef _WIN64 #undef imageOffset #endif } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); #ifdef _WIN64 *patchAddrHL += (DWORD)delta; #else *patchAddrHL += delta; #endif break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result = 1; ULONG_PTR lpCookie = 0; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); PIMAGE_DATA_DIRECTORY resource = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_RESOURCE); if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); + // Following will be used to resolve manifest in module - PIMAGE_RESOURCE_DIRECTORY resDir = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + resource->VirtualAddress); - PIMAGE_RESOURCE_DIRECTORY resDirTemp; - PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY)); - PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntryTemp; - PIMAGE_RESOURCE_DATA_ENTRY resDataEntry; - - // ACTCTX Structure, not used members must be set to 0! - ACTCTX actctx ={0,0,0,0,0,0,0,0,0}; - actctx.cbSize = sizeof(actctx); - HANDLE hActCtx; - - // Path to temp directory + our temporary file name - CHAR buf[MAX_PATH]; - DWORD tempPathLength = GetTempPathA(MAX_PATH, buf); - memcpy(buf + tempPathLength,"AutoHotkey.MemoryModule.temp.manifest",37); - actctx.lpSource = buf; - - // Enumerate Resources - int i = 0; - for (;i < resDir->NumberOfIdEntries + resDir->NumberOfNamedEntries;i++) + if (resource->Size) { - // Resolve current entry - resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY) + (i*sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))); - - // If entry is directory and Id is 24 = RT_MANIFEST - if (resDirEntry->DataIsDirectory && resDirEntry->Id == 24) + PIMAGE_RESOURCE_DIRECTORY resDir = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + resource->VirtualAddress); + PIMAGE_RESOURCE_DIRECTORY resDirTemp; + PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) ((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY)); + PIMAGE_RESOURCE_DIRECTORY_ENTRY resDirEntryTemp; + PIMAGE_RESOURCE_DATA_ENTRY resDataEntry; + + // ACTCTX Structure, not used members must be set to 0! + ACTCTX actctx ={0,0,0,0,0,0,0,0,0}; + actctx.cbSize = sizeof(actctx); + HANDLE hActCtx; + + // Path to temp directory + our temporary file name + CHAR buf[MAX_PATH]; + DWORD tempPathLength = GetTempPathA(MAX_PATH, buf); + memcpy(buf + tempPathLength,"AutoHotkey.MemoryModule.temp.manifest",37); + actctx.lpSource = buf; + + // Enumerate Resources + int i = 0; + for (;i < resDir->NumberOfIdEntries + resDir->NumberOfNamedEntries;i++) { - resDirTemp = (PIMAGE_RESOURCE_DIRECTORY)((char*)resDir + (resDirEntry->OffsetToDirectory)); - resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntry->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); - resDirTemp = (PIMAGE_RESOURCE_DIRECTORY) ((char*)resDir + (resDirEntryTemp->OffsetToDirectory)); - resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntryTemp->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); - resDataEntry = (PIMAGE_RESOURCE_DATA_ENTRY) ((char*)resDir + (resDirEntryTemp->OffsetToData)); - - // Write manifest to temportary file - // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk - // It will be deleted after CreateActCtx has been called. - HANDLE hFile = CreateFile(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); - if (hFile == INVALID_HANDLE_VALUE) - { -#if DEBUG_OUTPUT - OutputDebugStringA("CreateFile failed.\n"); -#endif - break; //failed to create file, continue and try loading without CreateActCtx - } - DWORD byteswritten = 0; - WriteFile(hFile,(codeBase + resDataEntry->OffsetToData),resDataEntry->Size,&byteswritten,NULL); - CloseHandle(hFile); - if (byteswritten == 0) + // Resolve current entry + resDirEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + sizeof(IMAGE_RESOURCE_DIRECTORY) + (i*sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))); + + // If entry is directory and Id is 24 = RT_MANIFEST + if (resDirEntry->DataIsDirectory && resDirEntry->Name == 24) { -#if DEBUG_OUTPUT - OutputDebugStringA("WriteFile failed.\n"); -#endif - break; //failed to write data, continue and try loading - } + resDirTemp = (PIMAGE_RESOURCE_DIRECTORY)((char*)resDir + (resDirEntry->OffsetToDirectory)); + resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntry->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); + resDirTemp = (PIMAGE_RESOURCE_DIRECTORY) ((char*)resDir + (resDirEntryTemp->OffsetToDirectory)); + resDirEntryTemp = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((char*)resDir + (resDirEntryTemp->OffsetToDirectory) + sizeof(IMAGE_RESOURCE_DIRECTORY)); + resDataEntry = (PIMAGE_RESOURCE_DATA_ENTRY) ((char*)resDir + (resDirEntryTemp->OffsetToData)); + + // Write manifest to temportary file + // Using FILE_ATTRIBUTE_TEMPORARY will avoid writing it to disk + // It will be deleted after CreateActCtx has been called. + HANDLE hFile = CreateFile(buf,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); + if (hFile == INVALID_HANDLE_VALUE) + { + #if DEBUG_OUTPUT + OutputDebugStringA("CreateFile failed.\n"); + #endif + break; //failed to create file, continue and try loading without CreateActCtx + } + DWORD byteswritten = 0; + WriteFile(hFile,(codeBase + resDataEntry->OffsetToData),resDataEntry->Size,&byteswritten,NULL); + CloseHandle(hFile); + if (byteswritten == 0) + { + #if DEBUG_OUTPUT + OutputDebugStringA("WriteFile failed.\n"); + #endif + break; //failed to write data, continue and try loading + } - hActCtx = CreateActCtx(&actctx); + hActCtx = CreateActCtx(&actctx); - // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) - hFile = CreateFileA(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); - CloseHandle(hFile); + // Open file and automatically delete on CloseHandle (FILE_FLAG_DELETE_ON_CLOSE) + hFile = CreateFileA(buf,GENERIC_WRITE,FILE_SHARE_DELETE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,NULL); + CloseHandle(hFile); - if (hActCtx == INVALID_HANDLE_VALUE) - break; //failed to create context, continue and try loading + if (hActCtx == INVALID_HANDLE_VALUE) + break; //failed to create context, continue and try loading - ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway - break; // Break since a dll can have only 1 manifest + ActivateActCtx(hActCtx,&lpCookie); // Don't care if this fails since we would countinue anyway + break; // Break since a dll can have only 1 manifest + } } } for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle; OutputDebugStringA((LPCSTR) (codeBase + importDesc->Name)); if (!(handle = LoadLibraryA((LPCSTR) (codeBase + importDesc->Name)))) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif result = 0; break; } #if DEBUG_OUTPUT #endif module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)IMAGE_ORDINAL(*thunkRef)); #endif } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); #if DEBUG_OUTPUT //OutputDebugStringA((LPCSTR)&thunkData->Name); #endif } if (*funcRef == 0) { result = 0; break; } } if (!result) { break; } } } if (lpCookie) DeactivateActCtx(0,lpCookie); return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("Not a valid executable file.\n"); #endif return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugStringA("No PE header found.\n"); #endif return NULL; } // reserve memory for image of library code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (code == NULL) { #if DEBUG_OUTPUT OutputLastError("Can't reserve memory"); #endif return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... VirtualAlloc(code, old_header->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // copy PE header to code memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections((const unsigned char*)data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { #if DEBUG_OUTPUT OutputDebugStringA("BuildImportTable failed.\n"); #endif goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugStringA("Library has no entry point.\n"); #endif goto error; } // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); if (!successfull) { #if DEBUG_OUTPUT - CHAR buf[1024]; OutputDebugStringA("Can't attach library.\n"); - _itoa((int)GetLastError(),buf,10); - OutputDebugStringA(buf); #endif goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module != NULL) { if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } if (module->modules != NULL) { // free previously opened libraries for (i=0; i<module->numModules; i++) { if (module->modules[i] != INVALID_HANDLE_VALUE) { FreeLibrary(module->modules[i]); } } free(module->modules); } if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); } HeapFree(GetProcessHeap(), 0, module); } }
tinku99/ahkdll
90e35fb1cb309435354f23ee413d875a988d7cb5
Fixed memory leak in DynaCall
diff --git a/source/script2.cpp b/source/script2.cpp index ad67be5..a1a9dfd 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -12620,1024 +12620,1029 @@ void *GetDllProcAddress(LPCTSTR aDllFileFunc, HMODULE *hmodule_to_free) // L31: } 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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } void BIF_CriticalObject(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj = (CriticalObject*)TokenToObject(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } IObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else obj->AddRef(); } // create new critical object and save reference CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed while (!TryEnterCriticalSection(this->lpCriticalSection)) MsgSleep(-1); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } void BIF_DynaCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParam[0]->symbol == SYM_OBJECT) { aParam[0]->object->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); } else if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // IObject *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } else if (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject()) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } ExprTokenType token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string[1]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE,TRUE); } else { return_type_string[0] = token.marker; } int i = 0; for (;return_type_string[0][i];i++) { if ( !(_tcschr(return_type_string[0]+i,'=') || ctoupper(return_type_string[0][i]) == 'U' || ctoupper(return_type_string[0][i]) == 'P' || (return_type_string[0][i] == '*')) )// Unsigned obj->marg_count++; } DYNAPARM *dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string[0],dyna_param)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string[0],'=')) { #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR retrurn_type_arg[3]; // maximal length of return type for (i=0;_tcschr(return_type_string[0] + i + 1,'=');i++) retrurn_type_arg[i] = return_type_string[0][i]; retrurn_type_arg[i] = '\0'; if (StrChrAny(retrurn_type_arg, _T("uU"))) { _tcsncpy(retrurn_type_arg,retrurn_type_arg + 1,sizeof(TCHAR)); _tcsncpy(retrurn_type_arg + 1,retrurn_type_arg + 2,sizeof(TCHAR)); //*(retrurn_type_arg + 2) = '\0'; obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(retrurn_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(retrurn_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); if (!obj->mfunction) { g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } // allocate memory for parameters and default parameters // in current design we need to have mdefault_param to be initialized // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before passing a buffer 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 (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters token = *aParam[1]; oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); if (aParam[1]->symbol != SYM_OBJECT) token.var->mObject->Invoke(result_token,token,IT_CALL,param,1); else token.object->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. if (result_token.value_int64 < 2) { obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } else { obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; if (aParam[1]->var->HasObject()) token.var->mObject->Invoke(result_token,token,IT_GET,param,1); else token.object->Invoke(result_token,token,IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } + else + { + obj->paramshift = (int*)malloc(sizeof(int)); + obj->paramshift[0] = NULL; + } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) { this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; continue; } ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = is_call; i < aParamCount; ++arg_count, i += 1) // Same loop as used in above, so maintain them together. { ExprTokenType &this_param = *aParam[i]; // Resolved for performance and convenience. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[arg_count+1] : arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } return OK; } void BIF_DllCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Stores a number or a SYM_STRING result in aResultToken. // Sets ErrorLevel to the error code appropriate to any problem that occurred. // 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) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); HMODULE hmodule_to_free = NULL; // Set default in case of early goto; mostly for maintainability. void *function; // Will hold the address of the function to be called. // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch(aParam[0]->symbol) { case SYM_STRING: // By far the most common, so it's listed first for performance. Also for performance, don't even consider the possibility that a quoted literal string like "33" is a function-address. function = NULL; // Indicate that no function has been specified yet. break; case SYM_VAR: // 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 = (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) ? (void *)aParam[0]->var->ToInt64(TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. // 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 ErrorLevel of 0xc0000005. //if (temp64 <= 0) //{ // g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. // return; //} //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; if (IS_NUMERIC(token.symbol) || token.symbol == SYM_OBJECT) // The return type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } LPTSTR return_type_string[2]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. } else { return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; }
tinku99/ahkdll
474222f1dc3133caa194167bcb8e018e2b3f8d96
Fixed memory leak in DynaCall
diff --git a/source/script2.cpp b/source/script2.cpp index 65e5479..ad67be5 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -12572,1071 +12572,1072 @@ bool IsDllArgTypeName(LPTSTR name) ConvertDllArgType(names, param); return param.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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } void BIF_CriticalObject(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj = (CriticalObject*)TokenToObject(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } IObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else obj->AddRef(); } // create new critical object and save reference CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed while (!TryEnterCriticalSection(this->lpCriticalSection)) MsgSleep(-1); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } void BIF_DynaCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParam[0]->symbol == SYM_OBJECT) { aParam[0]->object->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); } else if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // IObject *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } else if (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject()) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } ExprTokenType token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string[1]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE,TRUE); } else { return_type_string[0] = token.marker; } int i = 0; for (;return_type_string[0][i];i++) { if ( !(_tcschr(return_type_string[0]+i,'=') || ctoupper(return_type_string[0][i]) == 'U' || ctoupper(return_type_string[0][i]) == 'P' || (return_type_string[0][i] == '*')) )// Unsigned obj->marg_count++; } DYNAPARM *dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string[0],dyna_param)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string[0],'=')) { #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR retrurn_type_arg[3]; // maximal length of return type for (i=0;_tcschr(return_type_string[0] + i + 1,'=');i++) retrurn_type_arg[i] = return_type_string[0][i]; retrurn_type_arg[i] = '\0'; if (StrChrAny(retrurn_type_arg, _T("uU"))) { _tcsncpy(retrurn_type_arg,retrurn_type_arg + 1,sizeof(TCHAR)); _tcsncpy(retrurn_type_arg + 1,retrurn_type_arg + 2,sizeof(TCHAR)); //*(retrurn_type_arg + 2) = '\0'; obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(retrurn_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(retrurn_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); if (!obj->mfunction) { g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } // allocate memory for parameters and default parameters // in current design we need to have mdefault_param to be initialized // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before passing a buffer 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 (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); this_dyna_param.ptr = pStr[i]->GetBuffer(); 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. if (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { // Find out the length of array containing the definition and shift info for parameters token = *aParam[1]; oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); if (aParam[1]->symbol != SYM_OBJECT) token.var->mObject->Invoke(result_token,token,IT_CALL,param,1); else token.object->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; // Set the length of array containing shift info for parameters, -1 for definition in first item. - obj->paramshift = (int*)malloc(result_token.value_int64*sizeof(int)); - if (obj->paramshift[0] = (int)result_token.value_int64-1) + if (result_token.value_int64 < 2) { + obj->paramshift = (int*)malloc(sizeof(int)); + obj->paramshift[0] = NULL; + } + else + { + obj->paramshift = (int*)malloc((obj->marg_count + 1) * sizeof(int)); + obj->paramshift[0] = (int)result_token.value_int64 - 1; for (i=0;i < obj->marg_count;i++) { // Set shift info for parameters if (i < obj->paramshift[0]) { oParam.value_int64 = i+2; if (aParam[1]->var->HasObject()) token.var->mObject->Invoke(result_token,token,IT_GET,param,1); else token.object->Invoke(result_token,token,IT_GET,param,1); if (!IS_NUMERIC(result_token.symbol)) { g_script.SetErrorLevelOrThrowInt(-2, _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } obj->paramshift[i+1] = (int)result_token.value_int64-1; } else { // Find next (not yet used) parameter int oNextParam = 0; for (int f = 1;;f = 1) { for (int v = 0;v <= obj->paramshift[0];v++) { if (obj->paramshift[v+1] == oNextParam) { oNextParam++; f = 0; break; } } if (f) break; } obj->paramshift[i+1] = oNextParam; } } } } - else - { - obj->paramshift = (int*)malloc(sizeof(int)); - obj->paramshift[0] = NULL; - } for (i=0;i < obj->marg_count;i++) { obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { free(paramshift); free(mdyna_param); free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { if (i >= aParamCount - is_call) { this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; continue; } ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = is_call; i < aParamCount; ++arg_count, i += 1) // Same loop as used in above, so maintain them together. { ExprTokenType &this_param = *aParam[i]; // Resolved for performance and convenience. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[arg_count+1] : arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } return OK; } void BIF_DllCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Stores a number or a SYM_STRING result in aResultToken. // Sets ErrorLevel to the error code appropriate to any problem that occurred. // 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) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); HMODULE hmodule_to_free = NULL; // Set default in case of early goto; mostly for maintainability. void *function; // Will hold the address of the function to be called. // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch(aParam[0]->symbol) { case SYM_STRING: // By far the most common, so it's listed first for performance. Also for performance, don't even consider the possibility that a quoted literal string like "33" is a function-address. function = NULL; // Indicate that no function has been specified yet. break; case SYM_VAR: // 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 = (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) ? (void *)aParam[0]->var->ToInt64(TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. // 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 ErrorLevel of 0xc0000005. //if (temp64 <= 0) //{ // g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. // return; //} //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; if (IS_NUMERIC(token.symbol) || token.symbol == SYM_OBJECT) // The return type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } LPTSTR return_type_string[2]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. } else { return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; }
tinku99/ahkdll
21af32703d101e2d64996bf40b7d327a89533176
Fixed shifting parameters in DynaCall and definition from var
diff --git a/source/MemoryModule.c b/source/MemoryModule.c index dfa6e15..464a694 100644 --- a/source/MemoryModule.c +++ b/source/MemoryModule.c @@ -1,488 +1,499 @@ /* * Memory DLL loading code * Version 0.0.2 * * Copyright (c) 2004-2011 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2011 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif #include <Windows.h> #include <winnt.h> #ifdef DEBUG_OUTPUT #include <stdio.h> #endif #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif #include "MemoryModule.h" typedef struct { PIMAGE_NT_HEADERS headers; unsigned char *codeBase; HMODULE *modules; int numModules; int initialized; } MEMORYMODULE, *PMEMORYMODULE; typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugString(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_READWRITE); - +#ifdef _WIN64 + section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; +#else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; +#endif memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); +#ifdef _WIN64 + section->Misc.PhysicalAddress = (DWORD)(POINTER_TYPE)dest; +#else section->Misc.PhysicalAddress = (POINTER_TYPE)dest; +#endif } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page") #endif ; } } #ifndef _WIN64 #undef imageOffset #endif } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); +#ifdef _WIN64 + *patchAddrHL += (DWORD)delta; +#else *patchAddrHL += delta; +#endif break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result=1; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle = LoadLibraryA((LPCSTR) (codeBase + importDesc->Name)); if (handle == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif result = 0; break; } module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); } if (*funcRef == 0) { result = 0; break; } } if (!result) { break; } } } return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("Not a valid executable file.\n"); #endif return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("No PE header found.\n"); #endif return NULL; } // reserve memory for image of library code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); if (code == NULL) { #if DEBUG_OUTPUT OutputLastError("Can't reserve memory"); #endif return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... VirtualAlloc(code, old_header->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_READWRITE); // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_READWRITE); // copy PE header to code memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections(data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugString("Library has no entry point.\n"); #endif goto error; } // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); if (!successfull) { #if DEBUG_OUTPUT OutputDebugString("Can't attach library.\n"); #endif goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { - if (stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { + if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module != NULL) { if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } if (module->modules != NULL) { // free previously opened libraries for (i=0; i<module->numModules; i++) { if (module->modules[i] != INVALID_HANDLE_VALUE) { FreeLibrary(module->modules[i]); } } free(module->modules); } if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); } HeapFree(GetProcessHeap(), 0, module); } } diff --git a/source/resources/AutoHotkey.rc.orig b/source/resources/AutoHotkey.rc.orig deleted file mode 100644 index 7456a6f..0000000 --- a/source/resources/AutoHotkey.rc.orig +++ /dev/null @@ -1,239 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -//#include "afxres.h" -#include <winresrc.h> - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// RT_MANIFEST -// - -#ifdef EMBED_MANIFEST // VC++ 2005 and later don't require the next line. -CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "AutoHotkey.exe.manifest" -#endif - -// TYPELIB -// ReleaseDll must be build before DebugDll to update .tlb file -#ifdef _USRDLL -#ifdef _WIN64 -1 TYPELIB "temp\\x64\\ReleaseDll\\AutoHotkey.tlb" -#else -#ifdef _UNICODE -1 TYPELIB "temp\\Win32\\ReleaseDll\\AutoHotkey.tlb" -#else -1 TYPELIB "temp\\Win32\\ReleaseDll(mbcs)\\AutoHotkey.tlb" -#endif -#endif -#endif - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "//#include ""afxres.h""\r\n" - "#include <winresrc.h>\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#ifndef MINIDLL -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU_MAIN MENU -BEGIN - POPUP "&File" - BEGIN - MENUITEM "&Reload Script\tCtrl+R", ID_FILE_RELOADSCRIPT - MENUITEM "&Edit Script\tCtrl+E", ID_FILE_EDITSCRIPT - MENUITEM "&Window Spy", ID_FILE_WINDOWSPY - MENUITEM SEPARATOR - MENUITEM "&Pause Script\tPause", ID_FILE_PAUSE - MENUITEM "&Suspend Hotkeys", ID_FILE_SUSPEND - MENUITEM SEPARATOR - MENUITEM "E&xit (Terminate Script)", ID_FILE_EXIT - END - POPUP "&View" - BEGIN - MENUITEM "&Lines most recently executed\tCtrl+L", ID_VIEW_LINES - MENUITEM "&Variables and their contents\tCtrl+V", ID_VIEW_VARIABLES - MENUITEM "&Hotkeys and their methods\tCtrl+H", ID_VIEW_HOTKEYS - MENUITEM "&Key history and script info\tCtrl+K", ID_VIEW_KEYHISTORY - MENUITEM SEPARATOR - MENUITEM "&Refresh\tF5", ID_VIEW_REFRESH - END - POPUP "&Help" - BEGIN - MENUITEM "&User Manual\tF1", ID_HELP_USERMANUAL - MENUITEM "&Web Site", ID_HELP_WEBSITE - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_MAIN ICON "icon_main.ico" -IDI_SUSPEND ICON "icon_suspend.ico" -IDI_PAUSE ICON "icon_pause.ico" -IDI_PAUSE_SUSPEND ICON "icon_pause_suspend.ico" -IDI_FILETYPE ICON "icon_filetype.ico" -IDI_TRAY_WIN9X ICON "icon_tray_win9x.ico" -IDI_TRAY_WIN9X_SUSPEND ICON "icon_tray_win9x_suspend.ico" -IDI_TRAY ICON "icon_tray.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_INPUTBOX DIALOGEX 0, 0, 210, 83 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | - WS_CAPTION | WS_SYSMENU | WS_THICKFRAME -CAPTION "Dialog" -FONT 10, "MS Shell Dlg", 400, 0, 0x0 -BEGIN - EDITTEXT IDC_INPUTEDIT,2,51,207,12,ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,51,67,31,12 - PUSHBUTTON "Cancel",IDCANCEL,129,67,31,12 - LTEXT "Prompt",IDC_INPUTPROMPT,3,2,205,48 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDR_ACCELERATOR1 ACCELERATORS -BEGIN - VK_F1, ID_HELP_USERMANUAL, VIRTKEY, NOINVERT - "H", ID_VIEW_HOTKEYS, VIRTKEY, CONTROL, NOINVERT - "K", ID_VIEW_KEYHISTORY, VIRTKEY, CONTROL, NOINVERT - "L", ID_VIEW_LINES, VIRTKEY, CONTROL, NOINVERT - VK_F5, ID_VIEW_REFRESH, VIRTKEY, NOINVERT - "V", ID_VIEW_VARIABLES, VIRTKEY, CONTROL, NOINVERT - VK_PAUSE, ID_FILE_PAUSE, VIRTKEY, NOINVERT - "E", ID_FILE_EDITSCRIPT, VIRTKEY, CONTROL, NOINVERT - "R", ID_FILE_RELOADSCRIPT, VIRTKEY, CONTROL, NOINVERT -END -#endif - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#include "..\ahkversion.h" - -VS_VERSION_INFO VERSIONINFO - FILEVERSION AHK_VERSION_N - PRODUCTVERSION AHK_VERSION_N - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN -#ifdef AUTOHOTKEYSC - VALUE "FileDescription", "" - VALUE "FileVersion", AHK_VERSION - VALUE "InternalName", "" - VALUE "LegalCopyright", "" - VALUE "OriginalFilename", "" - VALUE "ProductName", "" - VALUE "ProductVersion", AHK_VERSION -#else - VALUE "FileDescription", "AutoHotkey_H" - VALUE "FileVersion", AHK_VERSION - VALUE "InternalName", "AutoHotkey_H" - VALUE "LegalCopyright", "Copyright (C) 2010" -#ifdef USRDLL - #ifdef MINIDLL - VALUE "OriginalFilename", "AutoHotkeyMini.dll" - #else - VALUE "OriginalFilename", "AutoHotkey.dll" - #endif -#else - VALUE "OriginalFilename", "AutoHotkey.exe" -#endif - VALUE "ProductName", "AutoHotkey_H" - VALUE "ProductVersion", AHK_VERSION -#endif - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - - -#ifdef _DEBUG -AHK RCDATA "Test\\Test.ahk" -#endif \ No newline at end of file diff --git a/source/script2.cpp b/source/script2.cpp index be38e23..65e5479 100644 --- a/source/script2.cpp +++ b/source/script2.cpp @@ -11525,2184 +11525,2229 @@ VarSizeType BIV_LoopFileDir(LPTSTR aBuf, LPTSTR aVarName) if (!aBuf) { if (last_backslash) *last_backslash = '\\'; // Restore the original value. return length; } _tcscpy(aBuf, file_dir); if (last_backslash) *last_backslash = '\\'; // Restore the original value. return length; } VarSizeType BIV_LoopFileFullPath(LPTSTR aBuf, LPTSTR aVarName) { // The loop handler already prepended the script's directory in cFileName for us: LPTSTR full_path = g->mLoopFile ? g->mLoopFile->cFileName : _T(""); if (aBuf) _tcscpy(aBuf, full_path); return (VarSizeType)_tcslen(full_path); } VarSizeType BIV_LoopFileLongPath(LPTSTR aBuf, LPTSTR aVarName) { TCHAR *unused, buf[MAX_PATH] = _T(""); // Set default. if (g->mLoopFile) { // GetFullPathName() is done in addition to ConvertFilespecToCorrectCase() for the following reasons: // 1) It's currently the only easy way to get the full path of the directory in which a file resides. // For example, if a script is passed a filename via command line parameter, that file could be // either an absolute path or a relative path. If relative, of course it's relative to A_WorkingDir. // The problem is, the script would have to manually detect this, which would probably take several // extra steps. // 2) A_LoopFileLongPath is mostly intended for the following cases, and in all of them it seems // preferable to have the full/absolute path rather than the relative path: // a) Files dragged onto a .ahk script when the drag-and-drop option has been enabled via the Installer. // b) Files passed into the script via command line. // The below also serves to make a copy because changing the original would yield // unexpected/inconsistent results in a script that retrieves the A_LoopFileFullPath // but only conditionally retrieves A_LoopFileLongPath. if (!GetFullPathName(g->mLoopFile->cFileName, MAX_PATH, buf, &unused)) *buf = '\0'; // It might fail if NtfsDisable8dot3NameCreation is turned on in the registry, and possibly for other reasons. else // The below is called in case the loop is being used to convert filename specs that were passed // in from the command line, which thus might not be the proper case (at least in the path // portion of the filespec), as shown in the file system: ConvertFilespecToCorrectCase(buf); } if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return (VarSizeType)_tcslen(buf); // Must explicitly calculate the length rather than using the return value from GetFullPathName(), because ConvertFilespecToCorrectCase() expands 8.3 path components. } VarSizeType BIV_LoopFileShortPath(LPTSTR aBuf, LPTSTR aVarName) // Unlike GetLoopFileShortName(), this function returns blank when there is no short path. // This is done so that there's a way for the script to more easily tell the difference between // an 8.3 name not being available (due to the being disabled in the registry) and the short // name simply being the same as the long name. For example, if short name creation is disabled // in the registry, A_LoopFileShortName would contain the long name instead, as documented. // But to detect if that short name is really a long name, A_LoopFileShortPath could be checked // and if it's blank, there is no short name available. { TCHAR buf[MAX_PATH] = _T(""); // Set default. DWORD length = 0; // if (g->mLoopFile) // The loop handler already prepended the script's directory in cFileName for us: if ( !(length = GetShortPathName(g->mLoopFile->cFileName, buf, MAX_PATH)) ) *buf = '\0'; // It might fail if NtfsDisable8dot3NameCreation is turned on in the registry, and possibly for other reasons. if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that (even though it's large enough to hold the string). This is true for ReadRegString()'s API call and may be true for other API calls like the one here. return (VarSizeType)length; } VarSizeType BIV_LoopFileTime(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[64]; LPTSTR target_buf = aBuf ? aBuf : buf; *target_buf = '\0'; // Set default. if (g->mLoopFile) { FILETIME ft; switch(ctoupper(aVarName[14])) // A_LoopFileTime[A]ccessed { case 'M': ft = g->mLoopFile->ftLastWriteTime; break; case 'C': ft = g->mLoopFile->ftCreationTime; break; default: ft = g->mLoopFile->ftLastAccessTime; } FileTimeToYYYYMMDD(target_buf, ft, true); } return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_LoopFileAttrib(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[64]; LPTSTR target_buf = aBuf ? aBuf : buf; *target_buf = '\0'; // Set default. if (g->mLoopFile) FileAttribToStr(target_buf, g->mLoopFile->dwFileAttributes); return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_LoopFileSize(LPTSTR aBuf, LPTSTR aVarName) { // Don't use MAX_INTEGER_LENGTH in case user has selected a very long float format via SetFormat. TCHAR str[128]; LPTSTR target_buf = aBuf ? aBuf : str; *target_buf = '\0'; // Set default. if (g->mLoopFile) { // UPDATE: 64-bit ints are now standard, so the following is obsolete: // It's a documented limitation that the size will show as negative if // greater than 2 gig, and will be wrong if greater than 4 gig. For files // that large, scripts should use the KB version of this function instead. // If a file is over 4gig, set the value to be the maximum size (-1 when // expressed as a signed integer, since script variables are based entirely // on 32-bit signed integers due to the use of ATOI(), etc.). //sprintf(str, "%d%", g->mLoopFile->nFileSizeHigh ? -1 : (int)g->mLoopFile->nFileSizeLow); ULARGE_INTEGER ul; ul.HighPart = g->mLoopFile->nFileSizeHigh; ul.LowPart = g->mLoopFile->nFileSizeLow; int divider; switch (ctoupper(aVarName[14])) // A_LoopFileSize[K/M]B { case 'K': divider = 1024; break; case 'M': divider = 1024*1024; break; default: divider = 0; } ITOA64((__int64)(divider ? ((unsigned __int64)ul.QuadPart / divider) : ul.QuadPart), target_buf); } return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_LoopRegType(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH] = _T(""); // Set default. if (g->mLoopRegItem) Line::RegConvertValueType(buf, MAX_PATH, g->mLoopRegItem->type); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that due to the zero-the-unused-part behavior of strlcpy/strncpy. return (VarSizeType)_tcslen(buf); } VarSizeType BIV_LoopRegKey(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[MAX_PATH] = _T(""); // Set default. if (g->mLoopRegItem) // Use root_key_type, not root_key (which might be a remote vs. local HKEY): Line::RegConvertRootKey(buf, MAX_PATH, g->mLoopRegItem->root_key_type); if (aBuf) _tcscpy(aBuf, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for aBuf can crash when aBuf is actually smaller than that due to the zero-the-unused-part behavior of strlcpy/strncpy. return (VarSizeType)_tcslen(buf); } VarSizeType BIV_LoopRegSubKey(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR str = g->mLoopRegItem ? g->mLoopRegItem->subkey : _T(""); if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_LoopRegName(LPTSTR aBuf, LPTSTR aVarName) { // This can be either the name of a subkey or the name of a value. LPTSTR str = g->mLoopRegItem ? g->mLoopRegItem->name : _T(""); if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_LoopRegTimeModified(LPTSTR aBuf, LPTSTR aVarName) { TCHAR buf[64]; LPTSTR target_buf = aBuf ? aBuf : buf; *target_buf = '\0'; // Set default. // Only subkeys (not values) have a time. In addition, Win9x doesn't support retrieval // of the time (nor does it store it), so make the var blank in that case: if (g->mLoopRegItem && g->mLoopRegItem->type == REG_SUBKEY && !g_os.IsWin9x()) FileTimeToYYYYMMDD(target_buf, g->mLoopRegItem->ftLastWriteTime, true); return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_LoopReadLine(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR str = g->mLoopReadFile ? g->mLoopReadFile->mCurrentLine : _T(""); if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_LoopField(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR str = g->mLoopField ? g->mLoopField : _T(""); if (aBuf) _tcscpy(aBuf, str); return (VarSizeType)_tcslen(str); } VarSizeType BIV_LoopIndex(LPTSTR aBuf, LPTSTR aVarName) { return aBuf ? (VarSizeType)_tcslen(ITOA64(g->mLoopIteration, aBuf)) // Must return exact length when aBuf isn't NULL. : MAX_INTEGER_LENGTH; // Probably performs better to return a conservative estimate for the first pass than to call ITOA64 for both passes. } VarSizeType BIV_ThisFunc(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR name; if (g->CurrentFunc) name = g->CurrentFunc->mName; else if (g->CurrentFuncGosub) // v1.0.48.02: For flexibility and backward compatibility, support A_ThisFunc even when a function Gosubs an external subroutine. name = g->CurrentFuncGosub->mName; else name = _T(""); if (aBuf) _tcscpy(aBuf, name); return (VarSizeType)_tcslen(name); } VarSizeType BIV_ThisLabel(LPTSTR aBuf, LPTSTR aVarName) { LPTSTR name = g->CurrentLabel ? g->CurrentLabel->mName : _T(""); if (aBuf) _tcscpy(aBuf, name); return (VarSizeType)_tcslen(name); } #ifndef MINIDLL VarSizeType BIV_ThisMenuItem(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, g_script.mThisMenuItemName); return (VarSizeType)_tcslen(g_script.mThisMenuItemName); } VarSizeType BIV_ThisMenuItemPos(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) // To avoid doing possibly high-overhead calls twice, merely return a conservative estimate for the first pass. return MAX_INTEGER_LENGTH; // The menu item's position is discovered through this process -- rather than doing // something higher performance such as storing the menu handle or pointer to menu/item // object in g_script -- because those things tend to be volatile. For example, a menu // or menu item object might be destroyed between the time the user selects it and the // time this variable is referenced in the script. Thus, by definition, this variable // contains the CURRENT position of the most recently selected menu item within its // CURRENT menu. if (*g_script.mThisMenuName && *g_script.mThisMenuItemName) { UserMenu *menu = g_script.FindMenu(g_script.mThisMenuName); if (menu) { // If the menu does not physically exist yet (perhaps due to being destroyed as a result // of DeleteAll, Delete, or some other operation), create it so that the position of the // item can be determined. This is done for consistency in behavior. if (!menu->mMenu) menu->Create(); UINT menu_item_pos = menu->GetItemPos(g_script.mThisMenuItemName); if (menu_item_pos < UINT_MAX) // Success return (VarSizeType)_tcslen(UTOA(menu_item_pos + 1, aBuf)); // +1 to convert from zero-based to 1-based. } } // Otherwise: *aBuf = '\0'; return 0; } VarSizeType BIV_ThisMenu(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, g_script.mThisMenuName); return (VarSizeType)_tcslen(g_script.mThisMenuName); } VarSizeType BIV_ThisHotkey(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, g_script.mThisHotkeyName); return (VarSizeType)_tcslen(g_script.mThisHotkeyName); } VarSizeType BIV_PriorHotkey(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) _tcscpy(aBuf, g_script.mPriorHotkeyName); return (VarSizeType)_tcslen(g_script.mPriorHotkeyName); } VarSizeType BIV_TimeSinceThisHotkey(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) // IMPORTANT: Conservative estimate because the time might change between 1st & 2nd calls. return MAX_INTEGER_LENGTH; // It must be the type of hotkey that has a label because we want the TimeSinceThisHotkey // value to be "in sync" with the value of ThisHotkey itself (i.e. use the same method // to determine which hotkey is the "this" hotkey): if (*g_script.mThisHotkeyName) // Even if GetTickCount()'s TickCount has wrapped around to zero and the timestamp hasn't, // DWORD subtraction still gives the right answer as long as the number of days between // isn't greater than about 49. See MyGetTickCount() for explanation of %d vs. %u. // Update: Using 64-bit ints now, so above is obsolete: //sntprintf(str, sizeof(str), "%d", (DWORD)(GetTickCount() - g_script.mThisHotkeyStartTime)); ITOA64((__int64)(GetTickCount() - g_script.mThisHotkeyStartTime), aBuf); else _tcscpy(aBuf, _T("-1")); return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_TimeSincePriorHotkey(LPTSTR aBuf, LPTSTR aVarName) { if (!aBuf) // IMPORTANT: Conservative estimate because the time might change between 1st & 2nd calls. return MAX_INTEGER_LENGTH; if (*g_script.mPriorHotkeyName) // See MyGetTickCount() for explanation for explanation: //sntprintf(str, sizeof(str), "%d", (DWORD)(GetTickCount() - g_script.mPriorHotkeyStartTime)); ITOA64((__int64)(GetTickCount() - g_script.mPriorHotkeyStartTime), aBuf); else _tcscpy(aBuf, _T("-1")); return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_EndChar(LPTSTR aBuf, LPTSTR aVarName) { if (aBuf) { if (g_script.mEndChar) *aBuf++ = g_script.mEndChar; //else we returned 0 previously, so MUST WRITE ONLY ONE NULL-TERMINATOR. *aBuf = '\0'; } return g_script.mEndChar ? 1 : 0; // v1.0.48.04: Fixed to support a NULL char, which happens when the hotstring has the "no ending character required" option. } VarSizeType BIV_Gui(LPTSTR aBuf, LPTSTR aVarName) // We're returning the length of the var's contents, not the size. { TCHAR buf[MAX_INTEGER_SIZE]; LPTSTR target_buf = aBuf ? aBuf : buf; if (!g->GuiWindow) // The current thread was not launched as a result of GUI action. { *target_buf = '\0'; return 0; } switch (ctoupper(aVarName[5])) { case 'W': // g->GuiPoint.x was overloaded to contain the size, since there are currently never any cases when // A_GuiX/Y and A_GuiWidth/Height are both valid simultaneously. It is documented that each of these // variables is defined only in proper types of subroutines. _itot(LOWORD(g->GuiPoint.x), target_buf, 10); // Above is always stored as decimal vs. hex, regardless of script settings. break; case 'H': _itot(HIWORD(g->GuiPoint.x), target_buf, 10); // See comments above. break; case 'X': _itot(g->GuiPoint.x, target_buf, 10); break; case 'Y': _itot(g->GuiPoint.y, target_buf, 10); break; case '\0': // A_Gui if (!*g->GuiWindow->mName) // v1.1.04: Anonymous GUI. return _stprintf(target_buf, _T("0x%Ix"), g->GuiWindow->mHwnd); if (aBuf) _tcscpy(aBuf, g->GuiWindow->mName); return _tcslen(g->GuiWindow->mName); } return (VarSizeType)_tcslen(target_buf); } VarSizeType BIV_GuiControl(LPTSTR aBuf, LPTSTR aVarName) { return GuiType::ControlGetName(g->GuiWindow, g->GuiControlIndex, aBuf); } VarSizeType BIV_GuiEvent(LPTSTR aBuf, LPTSTR aVarName) // We're returning the length of the var's contents, not the size. { global_struct &g = *::g; // Reduces code size and may improve performance. if (g.GuiEvent == GUI_EVENT_DROPFILES) { GuiType *pgui; UINT u, file_count; // GUI_EVENT_DROPFILES should mean that g.GuiWindow != NULL, but the below will double check that in // case g.GuiEvent can ever be set to that value as a result of receiving a bogus message in the queue. if (!(pgui = g.GuiWindow) // The current thread was not launched as a result of GUI action or this is a bogus msg. || !pgui->mHwnd // Gui window no longer exists. Relies on short-circuit boolean. || !pgui->mHdrop // No HDROP (probably impossible unless g.GuiEvent was given a bogus value somehow). || !(file_count = DragQueryFile(pgui->mHdrop, 0xFFFFFFFF, NULL, 0))) // No files in the drop (not sure if this is possible). // All of the above rely on short-circuit boolean order. { // Make the dropped-files list blank since there is no HDROP to query (or no files in it). if (aBuf) *aBuf = '\0'; return 0; } // Above has ensured that file_count > 0 if (aBuf) { TCHAR buf[MAX_PATH], *cp = aBuf; UINT length; for (u = 0; u < file_count; ++u) { length = DragQueryFile(pgui->mHdrop, u, buf, MAX_PATH); // MAX_PATH is arbitrary since aBuf is already known to be large enough. _tcscpy(cp, buf); // v1.0.47: Must be done as a separate copy because passing a size of MAX_PATH for something that isn't actually that large (though clearly large enough) due to previous size-estimation phase) can crash because the API may read/write data beyond what it actually needs. cp += length; if (u < file_count - 1) // i.e omit the LF after the last file to make parsing via "Loop, Parse" easier. *cp++ = '\n'; // Although the transcription of files on the clipboard into their text filenames is done // with \r\n (so that they're in the right format to be pasted to other apps as a plain text // list), it seems best to use a plain linefeed for dropped files since they won't be going // onto the clipboard nearly as often, and `n is easier to parse. Also, a script array isn't // used because large file lists would then consume a lot more of memory because arrays // are permanent once created, and also there would be wasted space due to the part of each // variable's capacity not used by the filename. } // No need for final termination of string because the last item lacks a newline. return (VarSizeType)(cp - aBuf); // This is the length of what's in the buffer. } else { VarSizeType total_length = 0; for (u = 0; u < file_count; ++u) total_length += DragQueryFile(pgui->mHdrop, u, NULL, 0); // Above: MSDN: "If the lpszFile buffer address is NULL, the return value is the required size, // in characters, of the buffer, not including the terminating null character." return total_length + file_count - 1; // Include space for a linefeed after each filename except the last. } // Don't call DragFinish() because this variable might be referred to again before this thread // is done. DragFinish() is called by MsgSleep() when the current thread finishes. } // Otherwise, this event is not GUI_EVENT_DROPFILES, so use standard modes of operation. static LPTSTR sNames[] = GUI_EVENT_NAMES; if (!aBuf) return (g.GuiEvent < GUI_EVENT_FIRST_UNNAMED) ? (VarSizeType)_tcslen(sNames[g.GuiEvent]) : 1; // Otherwise: if (g.GuiEvent < GUI_EVENT_FIRST_UNNAMED) return (VarSizeType)_tcslen(_tcscpy(aBuf, sNames[g.GuiEvent])); else // g.GuiEvent is assumed to be an ASCII value, such as a digit. This supports Slider controls. { *aBuf++ = (TCHAR)(UCHAR)g.GuiEvent; *aBuf = '\0'; return 1; } } #endif VarSizeType BIV_EventInfo(LPTSTR aBuf, LPTSTR aVarName) // We're returning the length of the var's contents, not the size. { return aBuf ? (VarSizeType)_tcslen(Exp32or64(UTOA,UTOA64)(g->EventInfo, aBuf)) // Must return exact length when aBuf isn't NULL. : MAX_INTEGER_LENGTH; } VarSizeType BIV_TimeIdle(LPTSTR aBuf, LPTSTR aVarName) // Called by multiple callers. { if (!aBuf) // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. return MAX_INTEGER_LENGTH; *aBuf = '\0'; // Set default. if (g_os.IsWin2000orLater()) // Checked in case the function is present in the OS but "not implemented". { // Must fetch it at runtime, otherwise the program can't even be launched on Win9x/NT: typedef BOOL (WINAPI *MyGetLastInputInfoType)(PLASTINPUTINFO); static MyGetLastInputInfoType MyGetLastInputInfo = (MyGetLastInputInfoType) GetProcAddress(GetModuleHandle(_T("user32")), "GetLastInputInfo"); if (MyGetLastInputInfo) { LASTINPUTINFO lii; lii.cbSize = sizeof(lii); if (MyGetLastInputInfo(&lii)) ITOA64(GetTickCount() - lii.dwTime, aBuf); } } return (VarSizeType)_tcslen(aBuf); } VarSizeType BIV_TimeIdlePhysical(LPTSTR aBuf, LPTSTR aVarName) // This is here rather than in script.h with the others because it depends on // hotkey.h and globaldata.h, which can't be easily included in script.h due to // mutual dependency issues. { // If neither hook is active, default this to the same as the regular idle time: #ifndef MINIDLL if (!(g_KeybdHook || g_MouseHook)) return BIV_TimeIdle(aBuf, _T("")); if (!aBuf) return MAX_INTEGER_LENGTH; // IMPORTANT: Conservative estimate because tick might change between 1st & 2nd calls. return (VarSizeType)_tcslen(ITOA64(GetTickCount() - g_TimeLastInputPhysical, aBuf)); // Switching keyboard layouts/languages sometimes sees to throw off the timestamps of the incoming events in the hook. #else return BIV_TimeIdle(aBuf, _T("")); #endif } +// CriticalObject Object +class CriticalObject : public ObjectBase +{ +protected: + IObject *object; + LPCRITICAL_SECTION lpCriticalSection; + CriticalObject() + : lpCriticalSection(0) + , object(0) + {} + + bool Delete(); + ~CriticalObject(){} + +public: + __int64 GetObj() + { + return (__int64)&*this->object; + } + __int64 GetCriSec() + { + return (__int64) this->lpCriticalSection; + } + static IObject *Create(ExprTokenType *aParam[], int aParamCount); + ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); +}; + //////////////////////// // BUILT-IN FUNCTIONS // //////////////////////// #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; bool passed_by_address; bool is_unsigned; // Allows return value and output parameters to be interpreted as unsigned vs. signed. }; -// CriticalObject Object -class CriticalObject : public ObjectBase -{ -protected: - IObject *object; - LPCRITICAL_SECTION lpCriticalSection; - CriticalObject() - : lpCriticalSection(0) - , object(0) - {} - - bool Delete(); - ~CriticalObject(){} - -public: - __int64 GetObj() - { - return (__int64)&*this->object; - } - __int64 GetCriSec() - { - return (__int64) this->lpCriticalSection; - } - static IObject *Create(ExprTokenType *aParam[], int aParamCount); - ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); -}; - // DynaCall Object class DynaToken : public ObjectBase { protected: int marg_count; #ifdef WIN32_PLATFORM int mdll_call_mode; #endif - int paramshift[MAX_NUMBER_SIZE]; + int *paramshift; void *mfunction; DYNAPARM *mdyna_param; + DYNAPARM *mdefault_param; DYNAPARM mreturn_attrib; DynaToken() : marg_count(0) #ifdef WIN32_PLATFORM , mdll_call_mode(0) #endif , mfunction(NULL), mdyna_param(NULL) , mreturn_attrib() {} bool Delete(); ~DynaToken(); public: static IObject *Create(ExprTokenType *aParam[], int aParamCount); ResultType STDMETHODCALLTYPE Invoke(ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount); }; #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 read_xmm0_float(); extern "C" double read_xmm0_double(); 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 DYNARESULT DynaCall(int aFlags, void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException , void *aRet, int aRetSize) #elif defined(_WIN64) DYNARESULT DynaCall(void *aFunction, DYNAPARM aParam[], int aParamCount, DWORD &aException) #else #error DllCall not supported on this platform #endif // Based on the code by Ton Plooy <[email protected]>. // 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}; // This struct is to be returned to caller by value. #ifdef WIN32_PLATFORM // Declaring all variables early should help minimize stack interference of C code with asm. DWORD *our_stack; int param_size; DWORD stack_dword, our_stack_size = 0; // Both might have to be DWORD for _asm. BYTE *cp; DWORD esp_start, esp_end, dwEAX, dwEDX; 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; _asm { mov our_stack, esp // our_stack is the location where we will write our args (bypassing "push"). 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. // Push the arg or its address onto the portion of the stack that was reserved for our use above. if (this_param.passed_by_address) { stack_dword = (DWORD)(size_t)&this_param.value_int; // Any union member would work. --our_stack; // ESP = ESP - 4 *our_stack = stack_dword; // SS:[ESP] = stack_dword our_stack_size += 4; // Keep track of how many bytes are on our reserved portion of the stack. } else // this_param's value is contained directly inside the union. { param_size = (this_param.type == DLL_ARG_INT64 || this_param.type == DLL_ARG_DOUBLE) ? 8 : 4; our_stack_size += param_size; // Must be done before our_stack_size is decremented below. Keep track of how many bytes are on our reserved portion of the stack. cp = (BYTE *)&this_param.value_int + param_size - 4; // Start at the right side of the arg and work leftward. while (param_size > 0) { stack_dword = *(DWORD *)cp; // Get first four bytes cp -= 4; // Next part of argument --our_stack; // ESP = ESP - 4 *our_stack = stack_dword; // SS:[ESP] = stack_dword param_size -= 4; } } } if ((aRet != NULL) && ((aFlags & DC_BORLAND) || (aRetSize > 8))) { // Return value isn't passed through registers, memory copy // is performed instead. Pass the pointer as hidden arg. our_stack_size += 4; // Add stack size --our_stack; // ESP = ESP - 4 *our_stack = (DWORD)(size_t)aRet; // 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 { add esp, reserved_stack_size // Restore to original position mov esp_start, esp // For detecting whether a DC_CALL_STD function was sent too many or too few args. sub esp, our_stack_size // 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 dwEAX, eax // Save eax/edx registers mov dwEDX, edx } // 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] else if (!aRet) { _asm { mov eax, [dwEAX] mov DWORD PTR [Res], eax mov edx, [dwEDX] mov DWORD PTR [Res + 4], edx } } else if (((aFlags & DC_BORLAND) == 0) && (aRetSize <= 8)) { // Microsoft optimized less than 8-bytes structure passing _asm { mov ecx, DWORD PTR [aRet] mov eax, [dwEAX] mov DWORD PTR [ecx], eax mov edx, [dwEDX] mov DWORD PTR [ecx + 4], edx } } #endif // WIN32_PLATFORM #ifdef _WIN64 int params_left = aParamCount; DWORD_PTR regArgs[4]; DWORD_PTR* stackArgs = NULL; size_t stackArgsSize = 0; // The first four parameters are passed in x64 through registers... like ARM :D for(int i = 0; (i < 4) && params_left; i++, params_left--) regArgs[i] = 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 // 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. if (esp_delta && (aFlags & DC_CALL_STD)) { *buf = 'A'; // The 'A' prefix indicates the call was made, but with too many or too few args. _itot(esp_delta, buf + 1, 10); g_script.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Assign buf not _itot()'s return value, which is the wrong location. } 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.SetErrorLevelOrThrowStr(buf, _T("DllCall")); // Positive ErrorLevel numbers are reserved for exception codes. } else g_ErrorLevel->Assign(ERRORLEVEL_NONE); return Res; } void ConvertDllArgType(LPTSTR aBuf[], DYNAPARM &aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[32]; int i; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf[0]; i < 2 && type_string; type_string = aBuf[++i]) { 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) { // The following also serves to set the default in case this is the first iteration. // Set default but perform second iteration in case the second type string isn't NULL. // In other words, if the second type string is explicitly valid rather than blank, // it should override the following default: aDynaParam.type = DLL_ARG_INVALID; // To assist with detection of errors like DllCall(...,flaot,n), treat empty string as an error; naked "CDecl" is now handled elsewhere. OBSOLETE COMMENT: Assume int. This is relied upon at least for having a return type such as a naked "CDecl". continue; // OK to do this regardless of whether this is the first or second iteration. } tcslcpy(buf, type_string, _countof(buf)); // Make a modifiable copy for easier parsing below. // v1.0.30.02: The addition of 'P' allows the quotes to be omitted around a pointer type. // However, the current detection below relies upon the fact that not 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; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsicmp(buf, _T(t))) aDynaParam.type = (n); TEST_TYPE("Int", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("Str", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("Ptr", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("Ptr", DLL_ARG_INT) #endif TEST_TYPE("Short", DLL_ARG_SHORT) TEST_TYPE("Char", DLL_ARG_CHAR) TEST_TYPE("Int64", DLL_ARG_INT64) TEST_TYPE("Float", DLL_ARG_FLOAT) TEST_TYPE("Double", DLL_ARG_DOUBLE) TEST_TYPE("AStr", DLL_ARG_ASTR) TEST_TYPE("WStr", DLL_ARG_WSTR) TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. { if (i > 0) // Second iteration. { // Reset flags to go with any blank value (i.e. !*buf) we're falling back to from the first iteration // (in case our iteration changed the flags based on bogus contents of the second type_string): aDynaParam.passed_by_address = false; aDynaParam.is_unsigned = false; //aDynaParam.type: The first iteration already set it to DLL_ARG_INT or DLL_ARG_INVALID. } else // First iteration, so aDynaParam.type's value will be set by the second (however, the loop's own condition will skip the second iteration if the second type_string is NULL). { aDynaParam.type = DLL_ARG_INVALID; // Set in case of: 1) the second iteration is skipped by the loop's own condition (since the caller doesn't always initialize "type"); or 2) the second iteration can't find a valid type. continue; } } // Since above didn't "continue", the type is explicitly valid so "return" to ensure that // the second iteration doesn't run (in case this is the first iteration): return; } } int ConvertDllArgTypes(LPTSTR aBuf, DYNAPARM *aDynaParam) // Helper function for DllCall(). Updates aDynaParam's type and other attributes. // Caller has ensured that aBuf contains exactly two strings (though the second can be NULL). { LPTSTR type_string; TCHAR buf[1024]; int i; int arg_count = 0; // Up to two iterations are done to cover the following cases: // No second type because there was no SYM_VAR to get it from: // blank means int // invalid is err // (for the below, note that 2nd can't be blank because var name can't be blank, and the first case above would have caught it if 2nd is NULL) // 1Blank, 2Invalid: blank (but ensure is_unsigned and passed_by_address get reset) // 1Blank, 2Valid: 2 // 1Valid, 2Invalid: 1 (second iteration would never have run, so no danger of it having erroneously reset is_unsigned/passed_by_address) // 1Valid, 2Valid: 1 (same comment) // 1Invalid, 2Invalid: invalid // 1Invalid, 2Valid: 2 for (i = 0, type_string = aBuf; *type_string; type_string = (aBuf + (++i))) { if (_tcschr(type_string,'=') || ctoupper(*type_string) == 'U' || (*type_string == '*') )// Unsigned continue; if (i>0 && ctoupper(*(aBuf + i - 1)) == 'U') // Unsigned aDynaParam[arg_count].is_unsigned = true; else aDynaParam[arg_count].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) break; tcslcpy(buf, type_string+1, 2); // Make a modifiable copy for easier parsing below. if (StrChrAny(buf, _T("*pP"))) // Additional validation: ensure nothing following the suffix. aDynaParam[arg_count].passed_by_address = true; else aDynaParam[arg_count].passed_by_address = false; tcslcpy(buf, type_string, 2); // Make a modifiable copy for easier parsing below. if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(buf, _T(t), 1)) aDynaParam[arg_count].type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else // It's non-blank but an unknown type. break; arg_count++; } return arg_count; } bool IsDllArgTypeName(LPTSTR name) // Test whether given name is a valid DllCall arg type (used by Script::MaybeWarnLocalSameAsGlobal). { LPTSTR names[] = { name, NULL }; DYNAPARM param; // An alternate method using an array of strings and tcslicmp in a loop benchmarked // slightly faster than this, but didn't seem worth the extra code size. This should // be more maintainable and is guaranteed to be consistent with what DllCall accepts. ConvertDllArgType(names, param); return param.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 ErrorLevel. ExpressionToPostfix passes NULL. g_script.SetErrorLevelOrThrowStr(_T("-3"), _T("DllCall")); // Stage 3 error: DLL couldn't be loaded. 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 set ErrorLevel. { // 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.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). } return function; } void BIF_CriticalObject(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; // If 2 parameters are given and second parameter is 1 or 2, // means we want to get the reference to obj(1) or crisec(2) if (aParamCount == 2 && TokenToInt64(*aParam[1]) < 3) { aResultToken.symbol = PURE_INTEGER; CriticalObject *criticalobj = (CriticalObject*)TokenToObject(*aParam[0]); if (criticalobj < (IObject *)1024) aResultToken.value_int64 = 0; else if (TokenToInt64(*aParam[1]) == 1) // Get object reference aResultToken.value_int64 = criticalobj->GetObj(); else if (TokenToInt64(*aParam[1]) == 2) // Get critical section reference aResultToken.value_int64 = criticalobj->GetCriSec(); } else if (obj = CriticalObject::Create(aParam,aParamCount)) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } IObject *CriticalObject::Create(ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParamCount == 0) // No parameters given, create new object obj = Object::Create(0,0); else if (IS_NUMERIC(aParam[0]->symbol) || IS_OPERAND(aParam[0]->symbol)) { obj = (IObject *)TokenToInt64(*aParam[0]); // object reference if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } if (!obj) // Check if it is an object or var containing object { obj = TokenToObject(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. return 0; else obj->AddRef(); } // create new critical object and save reference CriticalObject *criticalobj = new CriticalObject(); criticalobj->object = obj; if (aParamCount < 2) { // no Critical Section reference was given, create one criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)malloc(sizeof(CRITICAL_SECTION)); InitializeCriticalSection(criticalobj->lpCriticalSection); } else // An already initialized Critical Section reference was given, use it criticalobj->lpCriticalSection = (LPCRITICAL_SECTION)TokenToInt64(*aParam[1]); return criticalobj; } // // CriticalObject::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool CriticalObject::Delete() { return ObjectBase::Delete(); } ResultType STDMETHODCALLTYPE CriticalObject::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Avoid deadlocking the process so messages can still be processed while (!TryEnterCriticalSection(this->lpCriticalSection)) MsgSleep(-1); // Invoke original object as if it was called ResultType r = this->object->Invoke(aResultToken,aThisToken,aFlags,aParam,aParamCount); LeaveCriticalSection(this->lpCriticalSection); return r; } void BIF_DynaCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) { IObject *obj = NULL; if (aParam[0]->symbol == SYM_OBJECT) { aParam[0]->object->Invoke(aResultToken,*aParam[0],IT_SET,aParam+1,aParamCount-1); } else if (aParamCount == 1) // L33: POTENTIALLY UNSAFE - Cast IObject address to object reference. { obj = (IObject *)TokenToInt64(*aParam[0]); if (obj < (IObject *)1024) // Prevent some obvious errors. obj = NULL; else obj->AddRef(); } else obj = DynaToken::Create(aParam, aParamCount); if (obj) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = obj; // DO NOT ADDREF: after we return, the only reference will be in aResultToken. } else { aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); } } // // DynaToken::Create - Called by BIF_DynaCall to create a new object, optionally passing key/value pairs to set. // IObject *DynaToken::Create(ExprTokenType *aParam[], int aParamCount) { DynaToken *obj = new DynaToken(); TCHAR buf[4096]; ExprTokenType result_token; result_token.symbol = SYM_STRING; result_token.marker = _T(""); result_token.mem_to_free = NULL; result_token.buf = buf; ExprTokenType oParam = {0}; ExprTokenType *param[1] = {&oParam}; if (obj && aParamCount) { ExprTokenType this_token; this_token.symbol = SYM_OBJECT; this_token.object = obj; // 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. #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif obj->mreturn_attrib.type = DLL_ARG_INT; // Check validity of this arg's return type: if (IS_NUMERIC(aParam[1]->symbol)) // The return type should be a string, not something purely numeric. { g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. return NULL; } else if (aParam[1]->symbol == SYM_OBJECT) { oParam.symbol = PURE_INTEGER; oParam.value_int64 =1; aParam[1]->object->Invoke(result_token,*aParam[1],IT_GET,param,1); if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) { - g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. + return NULL; + } + } + else if (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject()) + { + oParam.symbol = PURE_INTEGER; + oParam.value_int64 =1; + aParam[1]->var->mObject->Invoke(result_token,*aParam[1],IT_GET,param,1); + if (IS_NUMERIC(result_token.symbol) || result_token.symbol == SYM_OBJECT) + { + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } - ExprTokenType token = (aParam[1]->symbol == SYM_OBJECT) ? result_token : *aParam[1]; + ExprTokenType token = (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) ? result_token : *aParam[1]; LPTSTR return_type_string[1]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE,TRUE); } else { return_type_string[0] = token.marker; } int i = 0; for (;return_type_string[0][i];i++) { if ( !(_tcschr(return_type_string[0]+i,'=') || ctoupper(return_type_string[0][i]) == 'U' || ctoupper(return_type_string[0][i]) == 'P' || (return_type_string[0][i] == '*')) )// Unsigned obj->marg_count++; } DYNAPARM *dyna_param = (DYNAPARM *)_alloca(obj->marg_count * sizeof(DYNAPARM)); if (obj->marg_count != ConvertDllArgTypes(return_type_string[0],dyna_param)) { - g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } if (_tcschr(return_type_string[0],'=')) { #ifdef WIN32_PLATFORM obj->mdll_call_mode = DC_CALL_CDECL; #endif obj->mreturn_attrib.type = DLL_ARG_INT; TCHAR retrurn_type_arg[3]; // maximal length of return type for (i=0;_tcschr(return_type_string[0] + i + 1,'=');i++) retrurn_type_arg[i] = return_type_string[0][i]; retrurn_type_arg[i] = '\0'; if (StrChrAny(retrurn_type_arg, _T("uU"))) { _tcsncpy(retrurn_type_arg,retrurn_type_arg + 1,sizeof(TCHAR)); _tcsncpy(retrurn_type_arg + 1,retrurn_type_arg + 2,sizeof(TCHAR)); //*(retrurn_type_arg + 2) = '\0'; obj->mreturn_attrib.is_unsigned = true; } else obj->mreturn_attrib.is_unsigned = false; if (StrChrAny(retrurn_type_arg + 1, _T("*pP"))) obj->mreturn_attrib.passed_by_address = true; else obj->mreturn_attrib.passed_by_address = false; if (false) {} // To simplify the macro below. It should have no effect on the compiled code. #define TEST_TYPE(t, n) else if (!_tcsnicmp(retrurn_type_arg, _T(t), 1)) obj->mreturn_attrib.type = (n); TEST_TYPE("I", DLL_ARG_INT) // The few most common types are kept up top for performance. TEST_TYPE("S", DLL_ARG_STR) #ifdef _WIN64 TEST_TYPE("T", DLL_ARG_INT64) // Ptr vs IntPtr to simplify recognition of the pointer suffix, to avoid any possible confusion with IntP, and because it is easier to type. #else TEST_TYPE("T", DLL_ARG_INT) #endif TEST_TYPE("H", DLL_ARG_SHORT) TEST_TYPE("C", DLL_ARG_CHAR) TEST_TYPE("6", DLL_ARG_INT64) TEST_TYPE("F", DLL_ARG_FLOAT) TEST_TYPE("D", DLL_ARG_DOUBLE) TEST_TYPE("A", DLL_ARG_ASTR) TEST_TYPE("W", DLL_ARG_WSTR) #undef TEST_TYPE else { - g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } } switch(aParam[0]->symbol) { case SYM_VAR: // 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. if (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) obj->mfunction = (void *)aParam[0]->var->ToInt64(TRUE); // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_INTEGER: obj->mfunction = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. return NULL; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). obj->mfunction = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } if (!obj->mfunction) obj->mfunction = GetDllProcAddress(aParam[0]->symbol == SYM_VAR ? aParam[0]->var->Contents() : aParam[0]->marker, NULL); if (!obj->mfunction) { - g_ErrorLevel->Assign(_T("-4")); // Stage 4 error: Function could not be found in the DLL(s). + g_script.SetErrorLevelOrThrowStr(_T("-4"), _T("DllCall")); // Stage 4 error: Function could not be found in the DLL(s). return NULL; } - + // allocate memory for parameters and default parameters + // in current design we need to have mdefault_param to be initialized + // it will be used instead of mdyna_param whenever parameters omitted obj->mdyna_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); + obj->mdefault_param = (DYNAPARM *)malloc(obj->marg_count * sizeof(DYNAPARM)); i = obj->marg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, i); for (i = 0; i < obj->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { ExprTokenType &this_param = ((aParamCount-2) > i) ? *aParam[i + 2] : *aParam[i]; // *aParam[i] will not be used DYNAPARM &this_dyna_param = dyna_param[i]; switch (this_dyna_param.type) { - case DLL_ARG_ASTR: + case DLL_ARG_STR: if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { // 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. - g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } // Otherwise, it's a supported type of string. - #ifdef UNICODE - pStr[i] = new CStringCharFromWChar(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); - this_dyna_param.astr = pStr[i]->GetBuffer(); - #else - this_dyna_param.astr = ((aParamCount-2) > i) ? TokenToString(this_param) : ""; // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). - #endif + this_dyna_param.ptr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); // 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 forget to call VarSetCapacity before psssing a buffer to some + // common for a script to forget to call VarSetCapacity before passing a buffer 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 = ""; // Make it read-only to force an exception. See comments above. + // this_dyna_param.str = _T(""); // Make it read-only to force an exception. See comments above. break; - case DLL_ARG_WSTR: + case DLL_ARG_xSTR: + // See the section above for comments. if (((aParamCount-2) > i) && IS_NUMERIC(this_param.symbol)) { - g_ErrorLevel->Assign(_T("-2")); + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; } - // Otherwise, it's a supported type of string. - #ifdef UNICODE - this_dyna_param.wstr = ((aParamCount-2) > i) ? TokenToString(this_param) : _T(""); - #else - pStr[i] = new CStringWCharFromChar(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); - this_dyna_param.wstr = pStr[i]->GetBuffer(); - #endif + // String needing translation: ASTR on Unicode build, WSTR on ANSI build. + pStr[i] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(((aParamCount-2) > i) ? TokenToString(this_param) : _T("")); + this_dyna_param.ptr = pStr[i]->GetBuffer(); + 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. this_dyna_param.value_double = ((aParamCount-2) > i) ? TokenToDouble(this_param) : 0; if (this_dyna_param.type == DLL_ARG_FLOAT) this_dyna_param.value_float = (float)this_dyna_param.value_double; break; case DLL_ARG_INVALID: - g_ErrorLevel->Assign(_T("-2")); // Stage 2 error: Invalid return type or arg type. + g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return NULL; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && (!((aParamCount-2) > i) || !IS_NUMERIC(this_param.symbol))) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = ((aParamCount-2) > i) ? (__int64)ATOU64(TokenToString(this_param)) : 0; // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = ((aParamCount-2) > i) ? TokenToInt64(this_param) : 0; // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. - if (aParam[1]->symbol == SYM_OBJECT) + if (aParam[1]->symbol == SYM_OBJECT || (aParam[1]->symbol == SYM_VAR && aParam[1]->var->HasObject())) { - token = *aParam[1]; + // Find out the length of array containing the definition and shift info for parameters + token = *aParam[1]; oParam.symbol = SYM_STRING; oParam.marker = _T("MaxIndex"); - token.object->Invoke(result_token,token,IT_CALL,param,1); - int oParamCount = (int)result_token.value_int64-1; + if (aParam[1]->symbol != SYM_OBJECT) + token.var->mObject->Invoke(result_token,token,IT_CALL,param,1); + else + token.object->Invoke(result_token,token,IT_CALL,param,1); oParam.symbol = PURE_INTEGER; - obj->paramshift[0] = oParamCount; - for (i=0;i < obj->marg_count;i++) + // Set the length of array containing shift info for parameters, -1 for definition in first item. + obj->paramshift = (int*)malloc(result_token.value_int64*sizeof(int)); + if (obj->paramshift[0] = (int)result_token.value_int64-1) { - if (i < oParamCount) + for (i=0;i < obj->marg_count;i++) { - oParam.value_int64 = i+2; - token.object->Invoke(result_token,token,IT_GET,param,1); - if (!IS_NUMERIC(result_token.symbol)) + // Set shift info for parameters + if (i < obj->paramshift[0]) { - g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. - return NULL; + oParam.value_int64 = i+2; + if (aParam[1]->var->HasObject()) + token.var->mObject->Invoke(result_token,token,IT_GET,param,1); + else + token.object->Invoke(result_token,token,IT_GET,param,1); + if (!IS_NUMERIC(result_token.symbol)) + { + g_script.SetErrorLevelOrThrowInt(-2, _T("DllCall")); // Stage 2 error: Invalid return type or arg type. + return NULL; + } + obj->paramshift[i+1] = (int)result_token.value_int64-1; + } + else + { // Find next (not yet used) parameter + int oNextParam = 0; + for (int f = 1;;f = 1) + { + for (int v = 0;v <= obj->paramshift[0];v++) + { + if (obj->paramshift[v+1] == oNextParam) + { + oNextParam++; + f = 0; + break; + } + } + if (f) + break; + } + obj->paramshift[i+1] = oNextParam; } - obj->paramshift[i+1] = (int)result_token.value_int64-1; } - else - obj->paramshift[i+1] = i-oParamCount; - } } else { + obj->paramshift = (int*)malloc(sizeof(int)); obj->paramshift[0] = NULL; } for (i=0;i < obj->marg_count;i++) + { + obj->mdefault_param[i] = dyna_param[i]; obj->mdyna_param[i] = dyna_param[i]; + } } return obj; } // // DynaToken::Delete - Called immediately before the object is deleted. // Returns false if object should not be deleted yet. // bool DynaToken::Delete() { return ObjectBase::Delete(); } DynaToken::~DynaToken() { + free(paramshift); free(mdyna_param); + free(mdefault_param); } ResultType STDMETHODCALLTYPE DynaToken::Invoke( ExprTokenType &aResultToken, ExprTokenType &aThisToken, int aFlags, ExprTokenType *aParam[], int aParamCount ) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); int arg_count = this->marg_count; int i = arg_count * sizeof(void *); #ifdef WIN32_PLATFORM int dll_call_mode = this->mdll_call_mode; #endif void *function = this->mfunction; DYNAPARM return_attrib = this->mreturn_attrib; // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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. int is_call = IS_INVOKE_CALL ? 1 : 0; - for (i = 0; i < aParamCount - is_call; i++) // Same loop as used in DynaToken::Create below, so maintain them together. + for (i = 0; i < this->marg_count; i++) // Same loop as used in DynaToken::Create below, so maintain them together. { + if (i >= aParamCount - is_call) + { + this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i] = this->mdefault_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; + continue; + } ExprTokenType &this_param = *aParam[i + is_call]; DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[i+1] : i]; - switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; } // 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 forget to call VarSetCapacity before passing a buffer 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 = ""; // Make it read-only to force an exception. See comments above. + // 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)) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); return OK; } // String needing translation: ASTR on Unicode build, WSTR on ANSI build. pStr[arg_count] = new UorA(CStringCharFromWChar,CStringWCharFromChar)(TokenToString(this_param)); this_dyna_param.ptr = pStr[arg_count]->GetBuffer(); 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. 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_INVALID: g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return OK; default: // Namely: //case DLL_ARG_INT: //case DLL_ARG_SHORT: //case DLL_ARG_CHAR: //case DLL_ARG_INT64: if (this_dyna_param.is_unsigned && this_dyna_param.type == DLL_ARG_INT64 && !IS_NUMERIC(this_param.symbol)) // The above and below also apply to BIF_NumPut(), so maintain them together. // !IS_NUMERIC() is checked because such tokens are already signed values, so should be // written out as signed so that whoever uses them can interpret negatives as large // unsigned values. // Support for unsigned values that are 32 bits wide or less is done via ATOI64() since // it should be able to handle both signed and unsigned values. However, unsigned 64-bit // values probably require ATOU64(), which will prevent something like -1 from being seen // as the largest unsigned 64-bit int; but more importantly there are some other issues // with unsigned 64-bit numbers: The script internals use 64-bit signed values everywhere, // so unsigned values can only be partially supported for incoming parameters, but probably // not for outgoing parameters (values the function changed) or the return value. Those // should probably be written back out to the script as negatives so that other parts of // the script, such as expressions, can see them as signed values. In other words, if the // script somehow gets a 64-bit unsigned value into a variable, and that value is larger // that LLONG_MAX (i.e. too large for ATOI64 to handle), ATOU64() will be able to resolve // it, but any output parameter should be written back out as a negative if it exceeds // LLONG_MAX (return values can be written out as unsigned since the script can specify // signed to avoid this, since they don't need the incoming detection for ATOU()). this_dyna_param.value_int64 = (__int64)ATOU64(TokenToString(this_param)); // Cast should not prevent called function from seeing it as an undamaged unsigned number. else this_dyna_param.value_int64 = TokenToInt64(this_param); // Values less than or equal to 32-bits wide always get copied into a single 32-bit value // because they should be right justified within it for insertion onto the call stack. if (this_dyna_param.type != DLL_ARG_INT64) // Shift the 32-bit value into the high-order DWORD of the 64-bit value for later use by DynaCall(). this_dyna_param.value_int = (int)this_dyna_param.value_int64; // Force a failure if compiler generates code for this that corrupts the union (since the same method is used for the more obscure float vs. double below). } // switch (this_dyna_param.type) } // for() each arg. //////////////////////// // 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 return_value = DynaCall(dll_call_mode, function, this->mdyna_param, arg_count, exception_occurred, NULL, 0); #endif #ifdef _WIN64 return_value = DynaCall(function, this->mdyna_param, arg_count, exception_occurred); #endif // The above has also set g_ErrorLevel appropriately. 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 ScriptErrror() so that the user knows *which* DllCall is at fault: g->InTryBlock = false; // do not throw an exception g_script.ScriptError(_T("This DllCall requires a prior VarSetCapacity. The program is now unstable and will exit.")); g_script.ExitApp(EXIT_CRITICAL); // Called this way, it will run the OnExit routine, which is debatable because it could cause more good than harm, but might avoid loss of data if the OnExit routine does something important. } // It seems best to have the above take precedence over "exception_occurred" below. if (exception_occurred) { // If the called function generated an exception, I think it's impossible for the return value // to be valid/meaningful since it the function never returned properly. Confirmation of this // would be good, but in the meantime it seems best to make the return value an empty string as // an indicator that the call failed (in addition to ErrorLevel). aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); // But continue on to write out any output parameters because the called function might have // had a chance to update them before aborting. } 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 = read_xmm0_float(); break; case DLL_ARG_DOUBLE: return_value.Double = read_xmm0_double(); 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. 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; // This is the default. 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 mem_to_free is NULL, so marker_length should be ignored. See next comment below. } //else leave aResultToken as it was set at the top of this function: an empty string. } break; case DLL_ARG_SHORT: 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: 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. 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; //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>. for (arg_count = 0, i = is_call; i < aParamCount; ++arg_count, i += 1) // Same loop as used in above, so maintain them together. { ExprTokenType &this_param = *aParam[i]; // Resolved for performance and convenience. if (this_param.symbol != SYM_VAR) // Output parameters are copied back only if its counterpart parameter is a naked variable. { if (pStr[arg_count]) // We don't need to copy it back, so delete it. delete pStr[arg_count]; continue; } DYNAPARM &this_dyna_param = this->mdyna_param[(this->paramshift[0] > 0) ? this->paramshift[arg_count+1] : arg_count]; // Resolved for performance and convenience. Var &output_var = *this_param.var; // if (this_dyna_param.type == DLL_ARG_STR) // Native string type for current build config. { LPTSTR contents = output_var.Contents(); // Contents() shouldn't update mContents in this case because Contents() was already called for each "str" parameter prior to calling the Dll function. VarSizeType capacity = output_var.Capacity(); // Since the performance cost is low, ensure the string is terminated at the limit of its // capacity (helps prevent crashes if DLL function didn't do its job and terminate the string, // or when a function is called that deliberately doesn't terminate the string, such as // RtlMoveMemory()). if (capacity) contents[capacity - 1] = '\0'; // The function might have altered Contents(), so update Length(). output_var.SetCharLength((VarSizeType)_tcslen(contents)); output_var.Close(); // Clear the attributes of the variable to reflect the fact that the contents may have changed. continue; } if (this_dyna_param.type == DLL_ARG_xSTR) // String needing translation: ASTR on Unicode build, WSTR on ANSI build. { pStr[arg_count]->ReleaseBuffer(); #ifdef UNICODE output_var.AssignStringFromCodePage( #else output_var.AssignStringToCodePage( #endif pStr[arg_count]->GetString() ); delete pStr[arg_count]; continue; } // Since above didn't "continue", this arg wasn't passed as a string. Of the remaining types, only // those passed by address can possibly be output parameters, so skip the rest: if (!this_dyna_param.passed_by_address) continue; switch (this_dyna_param.type) { // case DLL_ARG_STR: Already handled above. case DLL_ARG_INT: if (this_dyna_param.is_unsigned) output_var.Assign((DWORD)this_dyna_param.value_int); else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x0000FFFF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int & 0x000000FF); // This also forces the value into the unsigned domain of a signed int. else // Signed. 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. output_var.Assign(this_dyna_param.value_int64); break; case DLL_ARG_FLOAT: output_var.Assign(this_dyna_param.value_float); break; case DLL_ARG_DOUBLE: output_var.Assign(this_dyna_param.value_double); break; } } return OK; } void BIF_DllCall(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Stores a number or a SYM_STRING result in aResultToken. // Sets ErrorLevel to the error code appropriate to any problem that occurred. // 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) { // Set default result in case of early return; a blank value: aResultToken.symbol = SYM_STRING; aResultToken.marker = _T(""); HMODULE hmodule_to_free = NULL; // Set default in case of early goto; mostly for maintainability. void *function; // Will hold the address of the function to be called. // Check that the mandatory first parameter (DLL+Function) is valid. // (load-time validation has ensured at least one parameter is present). switch(aParam[0]->symbol) { case SYM_STRING: // By far the most common, so it's listed first for performance. Also for performance, don't even consider the possibility that a quoted literal string like "33" is a function-address. function = NULL; // Indicate that no function has been specified yet. break; case SYM_VAR: // 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 = (aParam[0]->var->IsNonBlankIntegerOrFloat() == PURE_INTEGER) ? (void *)aParam[0]->var->ToInt64(TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. // 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 ErrorLevel of 0xc0000005. //if (temp64 <= 0) //{ // g_ErrorLevel->Assign(_T("-1")); // Stage 1 error: Invalid first param. // return; //} //// Otherwise, assume it's a valid address: // function = (void *)temp64; break; case SYM_INTEGER: function = (void *)aParam[0]->value_int64; // For simplicity and due to rarity, this doesn't check for zero or negative numbers. break; case SYM_FLOAT: g_script.SetErrorLevelOrThrowStr(_T("-1"), _T("DllCall")); // Stage 1 error: Invalid first param. return; default: // SYM_OPERAND (SYM_OPERAND is typically a numeric literal). function = (TokenIsPureNumeric(*aParam[0]) == PURE_INTEGER) ? (void *)TokenToInt64(*aParam[0], TRUE) // For simplicity and due to rarity, this doesn't check for zero or negative numbers. : NULL; // Not a pure integer, so fall back to normal method of considering it to be path+name. } // 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. #ifdef WIN32_PLATFORM int dll_call_mode = DC_CALL_STD; // Set default. Can be overridden to DC_CALL_CDECL and flags can be OR'd into it. #endif if (aParamCount % 2) // Odd number of parameters indicates the return type has been omitted, so assume BOOL/INT. return_attrib.type = DLL_ARG_INT; else { // Check validity of this arg's return type: ExprTokenType &token = *aParam[aParamCount - 1]; if (IS_NUMERIC(token.symbol) || token.symbol == SYM_OBJECT) // The return type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } LPTSTR return_type_string[2]; if (token.symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { return_type_string[0] = token.var->Contents(TRUE, TRUE); return_type_string[1] = token.var->mName; // v1.0.33.01: Improve convenience by falling back to the variable's name if the contents are not appropriate. } else { return_type_string[0] = token.marker; return_type_string[1] = NULL; // Added in 1.0.48. } // 64-bit note: The calling convention detection code is preserved here for script compatibility. if (!_tcsnicmp(return_type_string[0], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[0] = omit_leading_whitespace(return_type_string[0] + 5); if (!*return_type_string[0]) { // 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; } } // This next part is a little iffy because if a legitimate return type is contained in a variable // that happens to be named Cdecl, Cdecl will be put into effect regardless of what's in the variable. // But the convenience of being able to omit the quotes around Cdecl seems to outweigh the extreme // rarity of such a thing happening. else if (return_type_string[1] && !_tcsnicmp(return_type_string[1], _T("CDecl"), 5)) // Alternate calling convention. { #ifdef WIN32_PLATFORM dll_call_mode = DC_CALL_CDECL; #endif return_type_string[1] += 5; // Support return type immediately following CDecl (this was previously supported _with_ quotes, though not documented). OBSOLETE COMMENT: Must be NULL since return_type_string[1] is the variable's name, by definition, so it can't have any spaces in it, and thus no space delimited items after "Cdecl". if (!*return_type_string[1]) // Pass default return type. Don't take shortcut approach used above as return_type_string[0] should take precedence if valid. return_type_string[1] = _T("Int"); } ConvertDllArgType(return_type_string, return_attrib); if (return_attrib.type == DLL_ARG_INVALID) { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } 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 } // Using stack memory, create an array of dll args large enough to hold the actual number of args present. int arg_count = aParamCount/2; // Might provide one extra due to first/last params, which is inconsequential. 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[2]; int i = arg_count * sizeof(void *); // for Unicode <-> ANSI charset conversion #ifdef UNICODE CStringA **pStr = (CStringA **) #else CStringW **pStr = (CStringW **) #endif _alloca(i); // _alloca vs malloc can make a significant difference to performance in some cases. memset(pStr, 0, 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 = 1; i < aParamCount; ++arg_count, i += 2) // Same loop as used later below, so maintain them together. { // Check validity of this arg's type and contents: if (IS_NUMERIC(aParam[i]->symbol)) // The arg type should be a string, not something purely numeric. { g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // Otherwise, this arg's type-name is a string as it should be, so retrieve it: if (aParam[i]->symbol == SYM_VAR) // SYM_VAR's Type() is always VAR_NORMAL (except lvalues in expressions). { arg_type_string[0] = aParam[i]->var->Contents(TRUE, TRUE); arg_type_string[1] = aParam[i]->var->mName; // v1.0.33.01: arg_type_string[1] improves convenience by falling back to the variable's name // if the contents are not appropriate. In other words, both Int and "Int" are treated the same. // It's done this way to allow the variable named "Int" to actually contain some other legitimate // type-name such as "Str" (in case anyone ever happens to do that). } else { arg_type_string[0] = aParam[i]->marker; arg_type_string[1] = NULL; } ExprTokenType &this_param = *aParam[i + 1]; // Resolved for performance and convenience. DYNAPARM &this_dyna_param = dyna_param[arg_count]; // // Store the each arg into a dyna_param struct, using its arg type to determine how. ConvertDllArgType(arg_type_string, this_dyna_param); switch (this_dyna_param.type) { case DLL_ARG_STR: if (IS_NUMERIC(this_param.symbol)) { // 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. g_script.SetErrorLevelOrThrowStr(_T("-2"), _T("DllCall")); // Stage 2 error: Invalid return type or arg type. return; } // 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
tinku99/ahkdll
9ffa3b14fecf3720749a68f8004d72a1b8154864
Small correction for sleep in send {100}
diff --git a/source/keyboard_mouse.cpp b/source/keyboard_mouse.cpp index 6b1315d..d85850e 100644 --- a/source/keyboard_mouse.cpp +++ b/source/keyboard_mouse.cpp @@ -2311,1025 +2311,1025 @@ void MouseClick(vk_type aVK, int aX, int aY, int aRepeatCount, int aSpeed, KeyEv // Remaining known limitations: // 1) Title bar buttons are not visibly in a pressed down state when a simulated click-down is sent // to them. // 2) A window that should not be activated, such as AlwaysOnTop+Disabled, is activated anyway // by SetForegroundWindowEx(). Not yet fixed due to its rarity and minimal consequences. // 3) A related problem for which no solution has been discovered (and perhaps it's too obscure // an issue to justify any added code size): If a remapping such as "F1::LButton" is in effect, // pressing and releasing F1 while the cursor is over a script window's title bar will cause the // window to move slightly the next time the mouse is moved. // 4) Clicking one of the script's window's title bar with a key/button that has been remapped to // become the left mouse button sometimes causes the button to get stuck down from the window's // point of view. The reasons are related to those in #1 above. In both #1 and #2, the workaround // is not at fault because it's not in effect then. Instead, the issue is that DefWindowProc enters // a non-msg-pumping loop while it waits for the user to drag-move the window. If instead the user // releases the button without dragging, the loop exits on its own after a 500ms delay or so. // 5) Obscure behavior caused by keyboard's auto-repeat feature: Use a key that's been remapped to // become the left mouse button to click and hold the minimize button of one of the script's windows. // Drag to the left. The window starts moving. This is caused by the fact that the down-click is // suppressed, thus the remap's hotkey subroutine thinks the mouse button is down, thus its // auto-repeat suppression doesn't work and it sends another click. POINT point; GetCursorPos(&point); // Assuming success seems harmless. // Despite what MSDN says, WindowFromPoint() appears to fetch a non-NULL value even when the // mouse is hovering over a disabled control (at least on XP). HWND child_under_cursor, parent_under_cursor; if ( (child_under_cursor = WindowFromPoint(point)) && (parent_under_cursor = GetNonChildParent(child_under_cursor)) // WM_NCHITTEST below probably requires parent vs. child. && GetWindowThreadProcessId(parent_under_cursor, NULL) == g_MainThreadID ) // It's one of our thread's windows. { LRESULT hit_test = SendMessage(parent_under_cursor, WM_NCHITTEST, 0, MAKELPARAM(point.x, point.y)); if ( aVK == VK_LBUTTON && (hit_test == HTCLOSE || hit_test == HTMAXBUTTON // Title bar buttons: Close, Maximize. || hit_test == HTMINBUTTON || hit_test == HTHELP) // Title bar buttons: Minimize, Help. || aVK == VK_RBUTTON && (hit_test == HTCAPTION || hit_test == HTSYSMENU) ) { if (aEventType == KEYDOWN) { // Ignore this event and substitute for it: Activate the window when one // of its title bar buttons is down-clicked. sWorkaroundVK = aVK; sWorkaroundHitTest = hit_test; SetForegroundWindowEx(parent_under_cursor); // Try to reproduce customary behavior. // For simplicity, aRepeatCount>1 is ignored and DoMouseDelay() is not done. return; } else // KEYUP { if (sWorkaroundHitTest == hit_test) // To weed out cases where user clicked down on a button then released somewhere other than the button. aEventType = KEYDOWNANDUP; // Translate this click-up into down+up to make up for the fact that the down was previously suppressed. //else let the click-up occur in case it does something or user wants it. } } } // Work-around for sending mouse clicks to one of our thread's own windows. } // sWorkaroundVK is reset later below. // Since above didn't return, the work-around isn't in effect and normal click(s) will be sent: if (aVK == VK_LBUTTON) { event_down = MOUSEEVENTF_LEFTDOWN; event_up = MOUSEEVENTF_LEFTUP; } else // aVK == VK_RBUTTON { event_down = MOUSEEVENTF_RIGHTDOWN; event_up = MOUSEEVENTF_RIGHTUP; } break; case VK_MBUTTON: event_down = MOUSEEVENTF_MIDDLEDOWN; event_up = MOUSEEVENTF_MIDDLEUP; break; case VK_XBUTTON1: case VK_XBUTTON2: event_down = MOUSEEVENTF_XDOWN; event_up = MOUSEEVENTF_XUP; event_data = (aVK == VK_XBUTTON1) ? XBUTTON1 : XBUTTON2; break; } // switch() // For simplicity and possibly backward compatibility, LONG_OPERATION_INIT/UPDATE isn't done. // In addition, some callers might do it for themselves, at least when aRepeatCount==1. for (int i = 0; i < aRepeatCount; ++i) { if (aEventType != KEYUP) // It's either KEYDOWN or KEYDOWNANDUP. { // v1.0.43: Reliability is significantly improved by specifying the coordinates with the event (if // caller gave us coordinates). This is mostly because of SetMouseDelay: In previously versions, // the delay between a MouseClick's move and its click allowed time for the user to move the mouse // away from the target position before the click was sent. MouseEvent(event_flags | event_down, event_data, aX, aY); // It ignores aX and aY when MOUSEEVENTF_MOVE is absent. // It seems best to always Sleep a certain minimum time between events // because the click-down event may cause the target app to do something which // changes the context or nature of the click-up event. AutoIt3 has also been // revised to do this. v1.0.40.02: Avoid doing the Sleep between the down and up // events when the workaround is in effect because any MouseDelay greater than 10 // would cause DoMouseDelay() to pump messages, which would defeat the workaround: if (!sWorkaroundVK) DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. } if (aEventType != KEYDOWN) // It's either KEYUP or KEYDOWNANDUP. { MouseEvent(event_flags | event_up, event_data, aX, aY); // It ignores aX and aY when MOUSEEVENTF_MOVE is absent. // It seems best to always do this one too in case the script line that caused // us to be called here is followed immediately by another script line which // is either another mouse click or something that relies upon the mouse click // having been completed: DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. } } // for() sWorkaroundVK = 0; // Reset this indicator in all cases except those for which above already returned. } void MouseMove(int &aX, int &aY, DWORD &aEventFlags, int aSpeed, bool aMoveOffset) // This function also does DoMouseDelay() for the caller. // This function converts aX and aY for the caller into MOUSEEVENTF_ABSOLUTE coordinates. // The exception is when the playback mode is in effect, in which case such a conversion would be undesirable // both here and by the caller. // It also puts appropriate bit-flags into aEventFlags. { // Most callers have already validated this, but some haven't. Since it doesn't take too long to check, // do it here rather than requiring all callers to do (helps maintainability). if (aX == COORD_UNSPECIFIED || aY == COORD_UNSPECIFIED) return; if (sSendMode == SM_PLAY) // Journal playback mode. { // Mouse speed (aSpeed) is ignored for SendInput/Play mode: the mouse always moves instantaneously // (though in the case of playback-mode, MouseDelay still applies between each movement and click). // Playback-mode ignores mouse speed because the cases where the user would want to move the mouse more // slowly (such as a demo) seem too rare to justify the code size and complexity, especially since the // incremental-move code would have to be implemented in the hook itself to ensure reliability. This is // because calling GetCursorPos() before playback begins could cause the mouse to wind up at the wrong // destination, especially if our thread is preempted while building the array (which would give the user // a chance to physically move the mouse before uninterruptibility begins). // For creating demonstrations that user slower mouse movement, the older MouseMove command can be used // in conjunction with BlockInput. This also applies to SendInput because it's conceivable that mouse // speed could be supported there (though it seems useless both visually and to improve reliability // because no mouse delays are possible within SendInput). // // MSG_OFFSET_MOUSE_MOVE is used to have the playback hook apply the offset (rather than doing it here // like is done for SendInput mode). This adds flexibility in cases where a new window becomes active // during playback, or the active window changes position -- if that were to happen, the offset would // otherwise be wrong while CoordMode is Relative because the changes can only be observed and // compensated for during playback. PutMouseEventIntoArray(MOUSEEVENTF_MOVE | (aMoveOffset ? MSG_OFFSET_MOUSE_MOVE : 0) , 0, aX, aY); // The playback hook uses normal vs. MOUSEEVENTF_ABSOLUTE coordinates. DoMouseDelay(); if (aMoveOffset) { // Now that we're done using the old values of aX and aY above, reset them to COORD_UNSPECIFIED // for the caller so that any subsequent clicks it does will be marked as "at current coordinates". aX = COORD_UNSPECIFIED; aY = COORD_UNSPECIFIED; } return; // Other parts below rely on this returning early to avoid converting aX/aY into MOUSEEVENTF_ABSOLUTE. } // The playback mode returned from above doesn't need these flags added because they're ignored for clicks: aEventFlags |= MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; // Done here for caller, for easier maintenance. POINT cursor_pos; if (aMoveOffset) // We're moving the mouse cursor relative to its current position. { if (sSendMode == SM_INPUT) { // Since GetCursorPos() can't be called to find out a future cursor position, use the position // tracked for SendInput (facilitates MouseClickDrag's R-option as well as Send{Click}'s). if (sSendInputCursorPos.x == COORD_UNSPECIFIED) // Initial/starting value hasn't yet been set. GetCursorPos(&sSendInputCursorPos); // Start it off where the cursor is now. aX += sSendInputCursorPos.x; aY += sSendInputCursorPos.y; } else { GetCursorPos(&cursor_pos); // None of this is done for playback mode since that mode already returned higher above. aX += cursor_pos.x; aY += cursor_pos.y; } } else { // Convert relative coords to screen coords if necessary (depends on CoordMode). // None of this is done for playback mode since that mode already returned higher above. CoordToScreen(aX, aY, COORD_MODE_MOUSE); } if (sSendMode == SM_INPUT) // Track predicted cursor position for use by subsequent events put into the array. { sSendInputCursorPos.x = aX; // Always stores normal coords (non-MOUSEEVENTF_ABSOLUTE). sSendInputCursorPos.y = aY; // } // Find dimensions of primary monitor. // Without the MOUSEEVENTF_VIRTUALDESK flag (supported only by SendInput, and then only on // Windows 2000/XP or later), MOUSEEVENTF_ABSOLUTE coordinates are relative to the primary monitor. int screen_width = GetSystemMetrics(SM_CXSCREEN); int screen_height = GetSystemMetrics(SM_CYSCREEN); // Convert the specified screen coordinates to mouse event coordinates (MOUSEEVENTF_ABSOLUTE). // MSDN: "In a multimonitor system, [MOUSEEVENTF_ABSOLUTE] coordinates map to the primary monitor." // The above implies that values greater than 65535 or less than 0 are appropriate, but only on // multi-monitor systems. For simplicity, performance, and backward compatibility, no check for // multi-monitor is done here. Instead, the system's default handling for out-of-bounds coordinates // is used; for example, mouse_event() stops the cursor at the edge of the screen. // UPDATE: In v1.0.43, the following formula was fixed (actually broken, see below) to always yield an // in-range value. The previous formula had a +1 at the end: // aX|Y = ((65535 * aX|Y) / (screen_width|height - 1)) + 1; // The extra +1 would produce 65536 (an out-of-range value for a single-monitor system) if the maximum // X or Y coordinate was input (e.g. x-position 1023 on a 1024x768 screen). Although this correction // seems inconsequential on single-monitor systems, it may fix certain misbehaviors that have been reported // on multi-monitor systems. Update: according to someone I asked to test it, it didn't fix anything on // multimonitor systems, at least those whose monitors vary in size to each other. In such cases, he said // that only SendPlay or DllCall("SetCursorPos") make mouse movement work properly. // FIX for v1.0.44: Although there's no explanation yet, the v1.0.43 formula is wrong and the one prior // to it was correct; i.e. unless +1 is present below, a mouse movement to coords near the upper-left corner of // the screen is typically off by one pixel (only the y-coordinate is affected in 1024x768 resolution, but // in other resolutions both might be affected). // v1.0.44.07: The following old formula has been replaced: // (((65535 * coord) / (width_or_height - 1)) + 1) // ... with the new one below. This is based on numEric's research, which indicates that mouse_event() // uses the following inverse formula internally: // x_or_y_coord = (x_or_y_abs_coord * screen_width_or_height) / 65536 #define MOUSE_COORD_TO_ABS(coord, width_or_height) (((65536 * coord) / width_or_height) + (coord < 0 ? -1 : 1)) aX = MOUSE_COORD_TO_ABS(aX, screen_width); aY = MOUSE_COORD_TO_ABS(aY, screen_height); // aX and aY MUST BE SET UNCONDITIONALLY because the output parameters must be updated for caller. // The incremental-move section further below also needs it. if (aSpeed < 0) // This can happen during script's runtime due to something like: MouseMove, X, Y, %VarContainingNegative% aSpeed = 0; // 0 is the fastest. else if (aSpeed > MAX_MOUSE_SPEED) aSpeed = MAX_MOUSE_SPEED; if (aSpeed == 0 || sSendMode == SM_INPUT) // Instantaneous move to destination coordinates with no incremental positions in between. { // See the comments in the playback-mode section at the top of this function for why SM_INPUT ignores aSpeed. MouseEvent(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, 0, aX, aY); DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. return; } // Since above didn't return, use the incremental mouse move to gradually move the cursor until // it arrives at the destination coordinates. // Convert the cursor's current position to mouse event coordinates (MOUSEEVENTF_ABSOLUTE). GetCursorPos(&cursor_pos); DoIncrementalMouseMove( MOUSE_COORD_TO_ABS(cursor_pos.x, screen_width) // Source/starting coords. , MOUSE_COORD_TO_ABS(cursor_pos.y, screen_height) // , aX, aY, aSpeed); // Destination/ending coords. } void MouseEvent(DWORD aEventFlags, DWORD aData, DWORD aX, DWORD aY) // Having this part outsourced to a function helps remember to use KEY_IGNORE so that our own mouse // events won't be falsely detected as hotkeys by the hooks (if they are installed). { if (sSendMode) PutMouseEventIntoArray(aEventFlags, aData, aX, aY); else mouse_event(aEventFlags , aX == COORD_UNSPECIFIED ? 0 : aX // v1.0.43.01: Must be zero if no change in position is desired , aY == COORD_UNSPECIFIED ? 0 : aY // (fixes compatibility with certain apps/games). , aData, KEY_IGNORE); } /////////////////////// // SUPPORT FUNCTIONS // /////////////////////// void PutKeybdEventIntoArray(modLR_type aKeyAsModifiersLR, vk_type aVK, sc_type aSC, DWORD aEventFlags, DWORD aExtraInfo) // This function is designed to be called from only one thread (the main thread) since it's not thread-safe. // Playback hook only supports sending neutral modifiers. Caller must ensure that any left/right modifiers // such as VK_RCONTROL are translated into neutral (e.g. VK_CONTROL). { bool key_up = aEventFlags & KEYEVENTF_KEYUP; // To make the SendPlay method identical in output to the other keystroke methods, have it generate // a leading down/up LControl event immediately prior to each RAlt event (with no key-delay). // This avoids having to add special handling to places like SetModifierLRState() to do AltGr things // differently when sending via playback vs. other methods. The event order recorded by the journal // record hook is a little different than what the low-level keyboard hook sees, but I don't think // the order should matter in this case: // sc vk key msg // 138 12 Alt syskeydown (right vs. left scan code) // 01d 11 Ctrl keydown (left scan code) <-- In keyboard hook, normally this precedes Alt, not follows it. Seems inconsequential (testing confirms). // 01d 11 Ctrl keyup (left scan code) // 138 12 Alt syskeyup (right vs. left scan code) // Check for VK_MENU not VK_RMENU because caller should have translated it to neutral: if (aVK == VK_MENU && aSC == SC_RALT && sTargetLayoutHasAltGr == CONDITION_TRUE && sSendMode == SM_PLAY) // Must pass VK_CONTROL rather than VK_LCONTROL because playback hook requires neutral modifiers. PutKeybdEventIntoArray(MOD_LCONTROL, VK_CONTROL, SC_LCONTROL, aEventFlags, aExtraInfo); // Recursive call to self. // Above must be done prior to the capacity check below because above might add a new array item. if (sEventCount == sMaxEvents) // Array's capacity needs expanding. if (!ExpandEventArray()) return; // Keep track of the predicted modifier state for use in other places: if (key_up) sEventModifiersLR &= ~aKeyAsModifiersLR; else sEventModifiersLR |= aKeyAsModifiersLR; if (sSendMode == SM_INPUT) { INPUT &this_event = sEventSI[sEventCount]; // For performance and convenience. this_event.type = INPUT_KEYBOARD; this_event.ki.wVk = aVK; this_event.ki.wScan = (aEventFlags & KEYEVENTF_UNICODE) ? aSC : LOBYTE(aSC); this_event.ki.dwFlags = aEventFlags; this_event.ki.dwExtraInfo = aExtraInfo; // Although our hook won't be installed (or won't detect, in the case of playback), that of other scripts might be, so set this for them. this_event.ki.time = 0; // Let the system provide its own timestamp, which might be more accurate for individual events if this will be a very long SendInput. #ifndef MINIDLL sHooksToRemoveDuringSendInput |= HOOK_KEYBD; // Presence of keyboard hook defeats uninterruptibility of keystrokes. #endif } else // Playback hook. { PlaybackEvent &this_event = sEventPB[sEventCount]; // For performance and convenience. if (!(aVK || aSC)) // Caller is signaling that aExtraInfo contains a delay/sleep event. { // Although delays at the tail end of the playback array can't be implemented by the playback // itself, caller wants them put in too. this_event.message = 0; // Message number zero flags it as a delay rather than an actual event. this_event.time_to_wait = aExtraInfo; } else // A normal (non-delay) event for playback. { // By monitoring incoming events in a message/event loop, the following key combinations were // confirmed to be WM_SYSKEYDOWN vs. WM_KEYDOWN (up events weren't tested, so are assumed to // be the same as down-events): // Alt+Win // Alt+Shift // Alt+Capslock/Numlock/Scrolllock // Alt+AppsKey // Alt+F2/Delete/Home/End/Arrow/BS // Alt+Space/Enter // Alt+Numpad (tested all digits & most other keys, with/without Numlock ON) // F10 (by itself) / Win+F10 / Alt+F10 / Shift+F10 (but not Ctrl+F10) // By contrast, the following are not SYS: Alt+Ctrl, Alt+Esc, Alt+Tab (the latter two // are never received by msg/event loop probably because the system intercepts them). // So the rule appears to be: It's a normal (non-sys) key if Alt isn't down and the key // isn't F10, or if Ctrl is down. Though a press of the Alt key itself is a syskey unless Ctrl is down. // Update: The release of ALT is WM_KEYUP vs. WM_SYSKEYUP when it modified at least one key while it was down. if (sEventModifiersLR & (MOD_LCONTROL | MOD_RCONTROL) // Control is down... || !(sEventModifiersLR & (MOD_LALT | MOD_RALT)) // ... or: Alt isn't down and this key isn't Alt or F10... && aVK != VK_F10 && !(aKeyAsModifiersLR & (MOD_LALT | MOD_RALT)) || (sEventModifiersLR & (MOD_LALT | MOD_RALT)) && key_up) // ... or this is the release of Alt (for simplicity, assume that Alt modified something while it was down). this_event.message = key_up ? WM_KEYUP : WM_KEYDOWN; else this_event.message = key_up ? WM_SYSKEYUP : WM_SYSKEYDOWN; this_event.vk = aVK; this_event.sc = aSC; // Don't omit the extended-key-bit because it is used later on. } } ++sEventCount; } void PutMouseEventIntoArray(DWORD aEventFlags, DWORD aData, DWORD aX, DWORD aY) // This function is designed to be called from only one thread (the main thread) since it's not thread-safe. // If the array-type is journal playback, caller should include MOUSEEVENTF_ABSOLUTE in aEventFlags if the // the mouse coordinates aX and aY are relative to the screen rather than the active window. { if (sEventCount == sMaxEvents) // Array's capacity needs expanding. if (!ExpandEventArray()) return; if (sSendMode == SM_INPUT) { INPUT &this_event = sEventSI[sEventCount]; // For performance and convenience. this_event.type = INPUT_MOUSE; this_event.mi.dx = (aX == COORD_UNSPECIFIED) ? 0 : aX; // v1.0.43.01: Must be zero if no change in position is this_event.mi.dy = (aY == COORD_UNSPECIFIED) ? 0 : aY; // desired (fixes compatibility with certain apps/games). this_event.mi.dwFlags = aEventFlags; this_event.mi.mouseData = aData; this_event.mi.dwExtraInfo = KEY_IGNORE; // Although our hook won't be installed (or won't detect, in the case of playback), that of other scripts might be, so set this for them. this_event.mi.time = 0; // Let the system provide its own timestamp, which might be more accurate for individual events if this will be a very long SendInput. #ifndef MINIDLL sHooksToRemoveDuringSendInput |= HOOK_MOUSE; // Presence of mouse hook defeats uninterruptibility of mouse clicks/moves. #endif } else // Playback hook. { // Note: Delay events (sleeps), which are supported in playback mode but not SendInput, are always inserted // via PutKeybdEventIntoArray() rather than this function. PlaybackEvent &this_event = sEventPB[sEventCount]; // For performance and convenience. // Determine the type of event specified by caller, but also omit MOUSEEVENTF_MOVE so that the // follow variations can be differentiated: // 1) MOUSEEVENTF_MOVE by itself. // 2) MOUSEEVENTF_MOVE with a click event or wheel turn (in this case MOUSEEVENTF_MOVE is permitted but // not required, since all mouse events in playback mode must have explicit coordinates at the // time they're played back). // 3) A click event or wheel turn by itself (same remark as above). // Bits are isolated in what should be a future-proof way (also omits MSG_OFFSET_MOUSE_MOVE bit). switch (aEventFlags & (0x1FFF & ~MOUSEEVENTF_MOVE)) // v1.0.48: 0x1FFF vs. 0xFFF to support MOUSEEVENTF_HWHEEL. { case 0: this_event.message = WM_MOUSEMOVE; break; // It's a movement without a click. // In cases other than the above, it's a click or wheel turn with optional WM_MOUSEMOVE too. case MOUSEEVENTF_LEFTDOWN: this_event.message = WM_LBUTTONDOWN; break; case MOUSEEVENTF_LEFTUP: this_event.message = WM_LBUTTONUP; break; case MOUSEEVENTF_RIGHTDOWN: this_event.message = WM_RBUTTONDOWN; break; case MOUSEEVENTF_RIGHTUP: this_event.message = WM_RBUTTONUP; break; case MOUSEEVENTF_MIDDLEDOWN: this_event.message = WM_MBUTTONDOWN; break; case MOUSEEVENTF_MIDDLEUP: this_event.message = WM_MBUTTONUP; break; case MOUSEEVENTF_XDOWN: this_event.message = WM_XBUTTONDOWN; break; case MOUSEEVENTF_XUP: this_event.message = WM_XBUTTONUP; break; case MOUSEEVENTF_WHEEL: this_event.message = WM_MOUSEWHEEL; break; case MOUSEEVENTF_HWHEEL: this_event.message = WM_MOUSEHWHEEL; break; // v1.0.48 // WHEEL: No info comes into journal-record about which direction the wheel was turned (nor by how many // notches). In addition, it appears impossible to specify such info when playing back the event. // Therefore, playback usually produces downward wheel movement (but upward in some apps like // Visual Studio). } // COORD_UNSPECIFIED_SHORT is used so that the very first event can be a click with unspecified // coordinates: it seems best to have the cursor's position fetched during playback rather than // here because if done here, there might be time for the cursor to move physically before // playback begins (especially if our thread is preempted while building the array). this_event.x = (aX == COORD_UNSPECIFIED) ? COORD_UNSPECIFIED_SHORT : (WORD)aX; this_event.y = (aY == COORD_UNSPECIFIED) ? COORD_UNSPECIFIED_SHORT : (WORD)aY; if (aEventFlags & MSG_OFFSET_MOUSE_MOVE) // Caller wants this event marked as a movement relative to cursor's current position. this_event.message |= MSG_OFFSET_MOUSE_MOVE; } ++sEventCount; } ResultType ExpandEventArray() // Returns OK or FAIL. { #define EVENT_EXPANSION_MULTIPLIER 2 // Should be very rare for array to need to expand more than a few times. size_t event_size = (sSendMode == SM_INPUT) ? sizeof(INPUT) : sizeof(PlaybackEvent); void *new_mem; // SendInput() appears to be limited to 5000 chars (10000 events in array), at least on XP. This is // either an undocumented SendInput limit or perhaps it's due to the system setting that determines // how many messages can get backlogged in each thread's msg queue before some start to get dropped. // Note that SendInput()'s return value always seems to indicate that all the characters were sent // even when the ones beyond the limit were clearly never received by the target window. // In any case, it seems best not to restrict to 5000 here in case the limit can vary for any reason. // The 5000 limit is documented in the help file. if ( !(new_mem = malloc(EVENT_EXPANSION_MULTIPLIER * sMaxEvents * event_size)) ) sAbortArraySend = true; // Usually better to send nothing rather than partial. // And continue on below to free the old block, if appropriate. else // Copy old array into new memory area (note that sEventSI and sEventPB are different views of the same variable). memcpy(new_mem, sEventSI, sEventCount * event_size); if (sMaxEvents > (sSendMode == SM_INPUT ? MAX_INITIAL_EVENTS_SI : MAX_INITIAL_EVENTS_PB)) free(sEventSI); // Previous block was malloc'd vs. _alloc'd, so free it. if (sAbortArraySend) return FAIL; sEventSI = (LPINPUT)new_mem; // Note that sEventSI and sEventPB are different views of the same variable. sMaxEvents *= EVENT_EXPANSION_MULTIPLIER; return OK; } void InitEventArray(void *aMem, UINT aMaxEvents, modLR_type aModifiersLR) { sEventPB = (PlaybackEvent *)aMem; // Sets sEventSI too, since both are the same. sMaxEvents = aMaxEvents; sEventModifiersLR = aModifiersLR; sSendInputCursorPos.x = COORD_UNSPECIFIED; sSendInputCursorPos.y = COORD_UNSPECIFIED; #ifndef MINIDLL sHooksToRemoveDuringSendInput = 0; #endif sEventCount = 0; sAbortArraySend = false; // If KeyEvent() ever sets it to true, that allows us to send nothing at all rather than a partial send. sFirstCallForThisEvent = true; // The above isn't a local static inside PlaybackProc because PlaybackProc might get aborted in the // middle of a NEXT/SKIP pair by user pressing Ctrl-Esc, etc, which would make it unreliable. } void SendEventArray(int &aFinalKeyDelay, modLR_type aModsDuringSend) // Caller must avoid calling this function if sMySendInput is NULL. // aFinalKeyDelay (which the caller should have initialized to -1 prior to calling) may be changed here // to the desired/final delay. Caller must not act upon it until changing sTypeOfHookToBuild to something // that will allow DoKeyDelay() to do a real delay. { if (sSendMode == SM_INPUT) { // Remove hook(s) temporarily because the presence of low-level (LL) keybd hook completely disables // the uninterruptibility of SendInput's keystrokes (but the mouse hook doesn't affect them). // The converse is also true. This was tested via: // #space:: // SendInput {Click 400, 400, 100} // MsgBox // ExitApp // ... and also with BurnK6 running, a CPU maxing utility. The mouse clicks were sent directly to the // BurnK6 window, and were pretty slow, and also I could physically move the mouse cursor a little // between each of sendinput's mouse clicks. But removing the mouse-hook during SendInputs solves all that. // Rather than removing both hooks unconditionally, it's better to // remove only those that actually have corresponding events in the array. This avoids temporarily // losing visibility of physical key states (especially when the keyboard hook is removed). #ifndef MINIDLL HookType active_hooks; if (active_hooks = GetActiveHooks()) AddRemoveHooks(active_hooks & ~sHooksToRemoveDuringSendInput, true); #endif // Caller has ensured that sMySendInput isn't NULL. // Following is done to support Sleep in Send e.g. Send, abc{100}def unsigned int aLastEventCount = 0; - for (unsigned int i = 0;i <= sEventCount;i++) + for (unsigned int i = 0;i < sEventCount;i++) { // wVK and wScan are 0 and dwExtraInfo holds time to sleep if (sEventSI[i].ki.wVk == 0 && sEventSI[i].ki.wScan == 0) { sMySendInput(i - aLastEventCount, &sEventSI[aLastEventCount], sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. SLEEP_WITHOUT_INTERRUPTION((int)sEventSI[i].ki.dwExtraInfo); aLastEventCount = i + 1; // + 1 to skip current item } } // Process unprocessed Events if (aLastEventCount == 0) sMySendInput(sEventCount, sEventSI, sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. else sMySendInput(aLastEventCount, &sEventSI[aLastEventCount], sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. // The return value is ignored because it never seems to be anything other than sEventCount, even if // the Send seems to partially fail (e.g. due to hitting 5000 event maximum). // Typical speed of SendInput: 10ms or less for short sends (under 100 events). // Typically 30ms for 500 events; and typically no more than 200ms for 5000 events (which is // the apparent max). // Testing shows that when SendInput returns to its caller, all of its key states are in effect // even if the target window hasn't yet had time to receive them all. For example, the // following reports that LShift is down: // SendInput {a 4900}{LShift down} // MsgBox % GetKeyState("LShift") // Furthermore, if the user manages to physically press or release a key during the call to // SendInput, testing shows that such events are in effect immediately when SendInput returns // to its caller, perhaps because SendInput clears out any backlog of physical keystrokes prior to // returning, or perhaps because the part of the OS that updates key states is a very high priority. #ifndef MINIDLL if (active_hooks) { if (active_hooks & sHooksToRemoveDuringSendInput & HOOK_KEYBD) // Keyboard hook was actually removed during SendInput. { // The above call to SendInput() has not only sent its own events, it has also emptied // the buffer of any events generated outside but during the SendInput. Since such // events are almost always physical events rather than simulated ones, it seems to do // more good than harm on average to consider any such changes to be physical. // The g_PhysicalKeyState array is also updated by GetModifierLRState(true), but only // for the modifier keys, not for all keys on the keyboard. Even if adjust all keys // is possible, it seems overly complex and it might impact performance more than it's // worth given the rarity of the user changing physical key states during a SendInput // and then wanting to explicitly retrieve that state via GetKeyState(Key, "P"). modLR_type mods_current = GetModifierLRState(true); // This also serves to correct the hook's logical modifiers, since hook was absent during the SendInput. modLR_type mods_changed_physically_during_send = aModsDuringSend ^ mods_current; g_modifiersLR_physical &= ~(mods_changed_physically_during_send & aModsDuringSend); // Remove those that changed from down to up. g_modifiersLR_physical |= mods_changed_physically_during_send & mods_current; // Add those that changed from up to down. g_HShwnd = GetForegroundWindow(); // An item done by ResetHook() that seems worthwhile here. // Most other things done by ResetHook() seem like they would do more harm than good to reset here // because of the the time the hook is typically missing is very short, usually under 30ms. } AddRemoveHooks(active_hooks, true); // Restore the hooks that were active before the SendInput. } #endif return; } // Since above didn't return, sSendMode == SM_PLAY. // It seems best not to call IsWindowHung() here because: // 1) It might improve script reliability to allow playback to a hung window because even though // the entire system would appear frozen, if the window becomes unhung, the keystrokes would // eventually get sent to it as intended (and the script may be designed to rely on this). // Furthermore, the user can press Ctrl-Alt-Del or Ctrl-Esc to unfreeze the system. // 2) It might hurt performance. // // During journal playback, it appears that LL hook receives events in realtime; its just that // keystrokes the hook passes through (or generates itself) don't actually hit the active window // until after the playback is done. Preliminary testing shows that the hook's disguise of Alt/Win // still function properly for Win/Alt hotkeys that use the playback method. sCurrentEvent = 0; // Reset for use by the hook below. Should be done BEFORE the hook is installed in the next line. #ifdef JOURNAL_RECORD_MODE // To record and analyze events via the above: // - Uncomment the line that defines this in the header file. // - Put breakpoint after the hook removes itself (a few lines below). Don't try to put breakpoint in RECORD hook // itself because it tends to freeze keyboard input (must press Ctrl-Alt-Del or Ctrl-Esc to unfreeze). // - Have the script send a keystroke (best to use non-character keystroke such as SendPlay {Shift}). // - It is now recording, so press the desired keys. // - Press Ctrl+Break, Ctrl-Esc, or Ctrl-Alt-Del to stop recording (which should then hit breakpoint below). // - Study contents of the sEventPB array, which contains the keystrokes just recorded. sEventCount = 0; // Used by RecordProc(). if ( !(g_PlaybackHook = SetWindowsHookEx(WH_JOURNALRECORD, RecordProc, GetModuleHandle(NULL), NULL)) ) return; #else if ( !(g_PlaybackHook = SetWindowsHookEx(WH_JOURNALPLAYBACK, PlaybackProc, GetModuleHandle(NULL), NULL)) ) return; // During playback, have the keybd hook (if it's installed) block presses of the Windows key. // This is done because the Windows key is about the only key (other than Ctrl-Esc or Ctrl-Alt-Del) // that takes effect immediately rather than getting buffered/postponed until after the playback. // It should be okay to set this after the playback hook is installed because playback shouldn't // actually begin until we have our thread do its first MsgSleep later below. g_BlockWinKeys = true; #endif // Otherwise, hook is installed, so: // Wait for the hook to remove itself because the script should not be allowed to continue // until the Send finishes. // GetMessage(single_msg_filter) can't be used because then our thread couldn't playback // keystrokes to one of its own windows. In addition, testing shows that it wouldn't // measurably improve performance anyway. // Note: User can't activate tray icon with mouse (because mouse is blocked), so there's // no need to call our main event loop merely to have the tray menu responsive. // Sleeping for 0 performs at least 15% worse than INTERVAL_UNSPECIFIED. I think this is // because the journal playback hook can operate only when this thread is in a message-pumping // state, and message pumping is far more efficient with GetMessage than PeekMessage. // Also note that both registered and hook hotkeys are noticed/caught during journal playback // (confirmed through testing). However, they are kept buffered until the Send finishes // because ACT_SEND and such are designed to be uninterruptible by other script threads; // also, it would be undesirable in almost any conceivable case. // // Use a loop rather than a single call to MsgSleep(WAIT_FOR_MESSAGES) because // WAIT_FOR_MESSAGES is designed only for use by WinMain(). The loop doesn't measurably // affect performance because there used to be the following here in place of the loop, // and it didn't perform any better: // GetMessage(&msg, NULL, WM_CANCELJOURNAL, WM_CANCELJOURNAL); while (g_PlaybackHook) SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED); // For maintainability, macro is used rather than optimizing/splitting the code it contains. g_BlockWinKeys = false; // Either the hook unhooked itself or the OS did due to Ctrl-Esc or Ctrl-Alt-Del. // MSDN: When an application sees a [system-generated] WM_CANCELJOURNAL message, it can assume // two things: the user has intentionally cancelled the journal record or playback mode, // and the system has already unhooked any journal record or playback hook procedures. if (!sEventPB[sEventCount - 1].message) // Playback hook can't do the final delay, so we do it here. // Don't do delay right here because the delay would be put into the array instead. aFinalKeyDelay = sEventPB[sEventCount - 1].time_to_wait; // GetModifierLRState(true) is not done because keystrokes generated by the playback hook // aren't really keystrokes in the sense that they affect global key state or modifier state. // They affect only the keystate retrieved when the target thread calls GetKeyState() // (GetAsyncKeyState can never see such changes, even if called from the target thread). // Furthermore, the hook (if present) continues to operate during journal playback, so it // will keep its own modifiers up-to-date if any physical or simulate keystrokes happen to // come in during playback (such keystrokes arrive in the hook in real time, but they don't // actually hit the active window until the playback finishes). } void CleanupEventArray(int aFinalKeyDelay) { if (sMaxEvents > (sSendMode == SM_INPUT ? MAX_INITIAL_EVENTS_SI : MAX_INITIAL_EVENTS_PB)) free(sEventSI); // Previous block was malloc'd vs. _alloc'd, so free it. Note that sEventSI and sEventPB are different views of the same variable. // The following must be done only after functions called above are done using it. But it must also be done // prior to our caller toggling capslock back on , to avoid the capslock keystroke from going into the array. sSendMode = SM_EVENT; DoKeyDelay(aFinalKeyDelay); // Do this only after resetting sSendMode above. Should be okay for mouse events too. } ///////////////////////////////// void DoKeyDelay(int aDelay) // Doesn't need to be thread safe because it should only ever be called from main thread. { if (aDelay < 0) // To support user-specified KeyDelay of -1 (fastest send rate). return; if (sSendMode) { if (sSendMode == SM_PLAY && aDelay > 0) // Zero itself isn't supported by playback hook, so no point in inserting such delays into the array. PutKeybdEventIntoArray(0, 0, 0, 0, aDelay); // Passing zero for vk and sc signals it that aExtraInfo contains the delay. //else for other types of arrays, never insert a delay or do one now. return; } if (g_os.IsWin9x()) { // Do a true sleep on Win9x because the MsgSleep() method is very inaccurate on Win9x // for some reason (a MsgSleep(1) causes a sleep between 10 and 55ms, for example): Sleep(aDelay); return; } SLEEP_WITHOUT_INTERRUPTION(aDelay); } void DoMouseDelay() // Helper function for the mouse functions below. { int mouse_delay = sSendMode == SM_PLAY ? g->MouseDelayPlay : g->MouseDelay; if (mouse_delay < 0) // To support user-specified KeyDelay of -1 (fastest send rate). return; if (sSendMode) { if (sSendMode == SM_PLAY && mouse_delay > 0) // Zero itself isn't supported by playback hook, so no point in inserting such delays into the array. PutKeybdEventIntoArray(0, 0, 0, 0, mouse_delay); // Passing zero for vk and sc signals it that aExtraInfo contains the delay. //else for other types of arrays, never insert a delay or do one now (caller should have already // checked that, so it's written this way here only for maintainability). return; } // I believe the varying sleep methods below were put in place to avoid issues when simulating // clicks on the script's own windows. There are extensive comments in MouseClick() and the // hook about these issues. Also, Sleep() is more accurate on Win9x than MsgSleep, which is // why it's used in that case. Here are more details from an older comment: // Always sleep a certain minimum amount of time between events to improve reliability, // but allow the user to specify a higher time if desired. Note that for Win9x, // a true Sleep() is done because it is much more accurate than the MsgSleep() method, // at least on Win98SE when short sleeps are done. UPDATE: A true sleep is now done // unconditionally if the delay period is small. This fixes a small issue where if // LButton is a hotkey that includes "MouseClick left" somewhere in its subroutine, // the script's own main window's title bar buttons for min/max/close would not // properly respond to left-clicks. By contrast, the following is no longer an issue // due to the dedicated thread in v1.0.39 (or more likely, due to an older change that // causes the tray menu to open upon RButton-up rather than down): // RButton is a hotkey that includes "MouseClick right" somewhere in its subroutine, // the user would not be able to correctly open the script's own tray menu via // right-click (note that this issue affected only the one script itself, not others). if (mouse_delay < 11 || (mouse_delay < 25 && g_os.IsWin9x())) Sleep(mouse_delay); else SLEEP_WITHOUT_INTERRUPTION(mouse_delay) } #ifndef MINIDLL void UpdateKeyEventHistory(bool aKeyUp, vk_type aVK, sc_type aSC) { if (!g_KeyHistory) // Don't access the array if it doesn't exist (i.e. key history is disabled). return; g_KeyHistory[g_KeyHistoryNext].key_up = aKeyUp; g_KeyHistory[g_KeyHistoryNext].vk = aVK; g_KeyHistory[g_KeyHistoryNext].sc = aSC; g_KeyHistory[g_KeyHistoryNext].event_type = 'i'; // Callers all want this. g_HistoryTickNow = GetTickCount(); g_KeyHistory[g_KeyHistoryNext].elapsed_time = (g_HistoryTickNow - g_HistoryTickPrev) / (float)1000; g_HistoryTickPrev = g_HistoryTickNow; HWND fore_win = GetForegroundWindow(); if (fore_win) { if (fore_win != g_HistoryHwndPrev) GetWindowText(fore_win, g_KeyHistory[g_KeyHistoryNext].target_window, _countof(g_KeyHistory[g_KeyHistoryNext].target_window)); else // i.e. avoid the call to GetWindowText() if possible. *g_KeyHistory[g_KeyHistoryNext].target_window = '\0'; } else _tcscpy(g_KeyHistory[g_KeyHistoryNext].target_window, _T("N/A")); g_HistoryHwndPrev = fore_win; // Update unconditionally in case it's NULL. if (++g_KeyHistoryNext >= g_MaxHistoryKeys) g_KeyHistoryNext = 0; } #endif ToggleValueType ToggleKeyState(vk_type aVK, ToggleValueType aToggleValue) // Toggle the given aVK into another state. For performance, it is the caller's responsibility to // ensure that aVK is a toggleable key such as capslock, numlock, insert, or scrolllock. // Returns the state the key was in before it was changed (but it's only a best-guess under Win9x). { // Can't use IsKeyDownAsync/GetAsyncKeyState() because it doesn't have this info: ToggleValueType starting_state = IsKeyToggledOn(aVK) ? TOGGLED_ON : TOGGLED_OFF; if (aToggleValue != TOGGLED_ON && aToggleValue != TOGGLED_OFF) // Shouldn't be called this way. return starting_state; if (starting_state == aToggleValue) // It's already in the desired state, so just return the state. return starting_state; if (aVK == VK_NUMLOCK) { #ifdef CONFIG_WIN9X if (g_os.IsWin9x()) { // For Win9x, we want to set the state unconditionally to be sure it's right. This is because // the retrieval of the Capslock state, for example, is unreliable, at least under Win98se // (probably due to lack of an AttachThreadInput() having been done). Although the // SetKeyboardState() method used by ToggleNumlockWin9x is not required for caps & scroll lock keys, // it is required for Numlock: ToggleNumlockWin9x(); return starting_state; // Best guess, but might be wrong. } #endif // Otherwise, NT/2k/XP: // Sending an extra up-event first seems to prevent the problem where the Numlock // key's indicator light doesn't change to reflect its true state (and maybe its // true state doesn't change either). This problem tends to happen when the key // is pressed while the hook is forcing it to be either ON or OFF (or it suppresses // it because it's a hotkey). Needs more testing on diff. keyboards & OSes: KeyEvent(KEYUP, aVK); } // Since it's not already in the desired state, toggle it: KeyEvent(KEYDOWNANDUP, aVK); // Fix for v1.0.40: IsKeyToggledOn()'s call to GetKeyState() relies on our thread having // processed messages. Confirmed necessary 100% of the time if our thread owns the active window. // v1.0.43: Extended the above fix to include all toggleable keys (not just Capslock) and to apply // to both directions (ON and OFF) since it seems likely to be needed for them all. bool our_thread_is_foreground; if (our_thread_is_foreground = (GetWindowThreadProcessId(GetForegroundWindow(), NULL) == g_MainThreadID)) // GetWindowThreadProcessId() tolerates a NULL hwnd. SLEEP_WITHOUT_INTERRUPTION(-1); if (aVK == VK_CAPITAL && aToggleValue == TOGGLED_OFF && IsKeyToggledOn(aVK)) { // Fix for v1.0.36.06: Since it's Capslock and it didn't turn off as attempted, it's probably because // the OS is configured to turn Capslock off only in response to pressing the SHIFT key (via Ctrl Panel's // Regional settings). So send shift to do it instead: KeyEvent(KEYDOWNANDUP, VK_SHIFT); if (our_thread_is_foreground) // v1.0.43: Added to try to achieve 100% reliability in all situations. SLEEP_WITHOUT_INTERRUPTION(-1); // Check msg queue to put SHIFT's turning off of Capslock into effect from our thread's POV. } return starting_state; } #ifdef CONFIG_WIN9X void ToggleNumlockWin9x() // Numlock requires a special method to toggle the state and its indicator light under Win9x. // Capslock and Scrolllock do not need this method, since keybd_event() works for them. { BYTE state[256]; GetKeyboardState((PBYTE)&state); state[VK_NUMLOCK] ^= 0x01; // Toggle the low-order bit to the opposite state. SetKeyboardState((PBYTE)&state); } //void CapslockOffWin9x() //{ // BYTE state[256]; // GetKeyboardState((PBYTE)&state); // state[VK_CAPITAL] &= ~0x01; // SetKeyboardState((PBYTE)&state); //} #endif /* void SetKeyState (vk_type vk, int aKeyUp) // Later need to adapt this to support Win9x by using SetKeyboardState for those OSs. { if (!vk) return; int key_already_up = !(GetKeyState(vk) & 0x8000); if ((key_already_up && aKeyUp) || (!key_already_up && !aKeyUp)) return; KeyEvent(aKeyUp, vk); } */ void SetModifierLRState(modLR_type aModifiersLRnew, modLR_type aModifiersLRnow, HWND aTargetWindow , bool aDisguiseDownWinAlt, bool aDisguiseUpWinAlt, DWORD aExtraInfo) // This function is designed to be called from only the main thread; it's probably not thread-safe. // Puts modifiers into the specified state, releasing or pressing down keys as needed. // The modifiers are released and pressed down in a very delicate order due to their interactions with // each other and their ability to show the Start Menu, activate the menu bar, or trigger the OS's language // bar hotkeys. Side-effects like these would occur if a more simple approach were used, such as releasing // all modifiers that are going up prior to pushing down the ones that are going down. // When the target layout has an altgr key, it is tempting to try to simplify things by removing MOD_LCONTROL // from aModifiersLRnew whenever aModifiersLRnew contains MOD_RALT. However, this a careful review how that // would impact various places below where sTargetLayoutHasAltGr is checked indicates that it wouldn't help. // Note that by design and as documented for ControlSend, aTargetWindow is not used as the target for the // various calls to KeyEvent() here. It is only used as a workaround for the GUI window issue described // at the bottom. { if (aModifiersLRnow == aModifiersLRnew) // They're already in the right state, so avoid doing all the checks. return; // Especially avoids the aTargetWindow check at the bottom. // Notes about modifier key behavior on Windows XP (these probably apply to NT/2k also, and has also // been tested to be true on Win98): The WIN and ALT keys are the problem keys, because if either is // released without having modified something (even another modifier), the WIN key will cause the // Start Menu to appear, and the ALT key will activate the menu bar of the active window (if it has one). // For example, a hook hotkey such as "$#c::Send text" (text must start with a lowercase letter // to reproduce the issue, because otherwise WIN would be auto-disguised as a side effect of the SHIFT // keystroke) would cause the Start Menu to appear if the disguise method below weren't used. // // Here are more comments formerly in SetModifierLRStateSpecific(), which has since been eliminated // because this function is sufficient: // To prevent it from activating the menu bar, the release of the ALT key should be disguised // unless a CTRL key is currently down. This is because CTRL always seems to avoid the // activation of the menu bar (unlike SHIFT, which sometimes allows the menu to be activated, // though this is hard to reproduce on XP). Another reason not to use SHIFT is that the OS // uses LAlt+Shift as a hotkey to switch languages. Such a hotkey would be triggered if SHIFT // were pressed down to disguise the release of LALT. // // Alt-down events are also disguised whenever they won't be accompanied by a Ctrl-down. // This is necessary whenever our caller does not plan to disguise the key itself. For example, // if "!a::Send Test" is a registered hotkey, two things must be done to avoid complications: // 1) Prior to sending the word test, ALT must be released in a way that does not activate the // menu bar. This is done by sandwiching it between a CTRL-down and a CTRL-up. // 2) After the send is complete, SendKeys() will restore the ALT key to the down position if // the user is still physically holding ALT down (this is done to make the logical state of // the key match its physical state, which allows the same hotkey to be fired twice in a row // without the user having to release and press down the ALT key physically). // The #2 case above is the one handled below by ctrl_wont_be_down. It is especially necessary // when the user releases the ALT key prior to releasing the hotkey suffix, which would otherwise // cause the menu bar (if any) of the active window to be activated. // // Some of the same comments above for ALT key apply to the WIN key. More about this issue: // Although the disguise of the down-event is usually not needed, it is needed in the rare case // where the user releases the WIN or ALT key prior to releasing the hotkey's suffix. // Although the hook could be told to disguise the physical release of ALT or WIN in these // cases, it's best not to rely on the hook since it is not always installed. // // Registered WIN and ALT hotkeys that don't use the Send command work okay except ALT hotkeys, // which if the user releases ALT prior the hotkey's suffix key, cause the menu bar to be activated. // Since it is unusual for users to do this and because it is standard behavior for ALT hotkeys // registered in the OS, fixing it via the hook seems like a low priority, and perhaps isn't worth // the added code complexity/size. But if there is ever a need to do so, the following note applies: // If the hook is installed, could tell it to disguise any need-to-be-disguised Alt-up that occurs // after receipt of the registered ALT hotkey. But what if that hotkey uses the send command: // there might be interference? Doesn't seem so, because the hook only disguises non-ignored events. // Set up some conditions so that the keystrokes that disguise the release of Win or Alt // are only sent when necessary (which helps avoid complications caused by keystroke interaction, // while improving performance): modLR_type aModifiersLRunion = aModifiersLRnow | aModifiersLRnew; // The set of keys that were or will be down. bool ctrl_not_down = !(aModifiersLRnow & (MOD_LCONTROL | MOD_RCONTROL)); // Neither CTRL key is down now. bool ctrl_will_not_be_down = !(aModifiersLRnew & (MOD_LCONTROL | MOD_RCONTROL)) // Nor will it be. && !(sTargetLayoutHasAltGr == CONDITION_TRUE && (aModifiersLRnew & MOD_RALT)); // Nor will it be pushed down indirectly due to AltGr. bool ctrl_nor_shift_nor_alt_down = ctrl_not_down // Neither CTRL key is down now. && !(aModifiersLRnow & (MOD_LSHIFT | MOD_RSHIFT | MOD_LALT | MOD_RALT)); // Nor is any SHIFT/ALT key. bool ctrl_or_shift_or_alt_will_be_down = !ctrl_will_not_be_down // CTRL will be down. || (aModifiersLRnew & (MOD_LSHIFT | MOD_RSHIFT | MOD_LALT | MOD_RALT)); // or SHIFT or ALT will be. // If the required disguise keys aren't down now but will be, defer the release of Win and/or Alt // until after the disguise keys are in place (since in that case, the caller wanted them down // as part of the normal operation here): bool defer_win_release = ctrl_nor_shift_nor_alt_down && ctrl_or_shift_or_alt_will_be_down; bool defer_alt_release = ctrl_not_down && !ctrl_will_not_be_down; // i.e. Ctrl not down but it will be. bool release_shift_before_alt_ctrl = defer_alt_release // i.e. Control is moving into the down position or... || !(aModifiersLRnow & (MOD_LALT | MOD_RALT)) && (aModifiersLRnew & (MOD_LALT | MOD_RALT)); // ...Alt is moving into the down position. // Concerning "release_shift_before_alt_ctrl" above: Its purpose is to prevent unwanted firing of the OS's // language bar hotkey. See the bottom of this function for more explanation. // ALT: bool disguise_alt_down = aDisguiseDownWinAlt && ctrl_not_down && ctrl_will_not_be_down; // Since this applies to both Left and Right Alt, don't take sTargetLayoutHasAltGr into account here. That is done later below. // WIN: The WIN key is successfully disguised under a greater number of conditions than ALT. // Since SendPlay can't display Start Menu, there's no need to send the disguise-keystrokes (such // keystrokes might cause unwanted effects in certain games): bool disguise_win_down = aDisguiseDownWinAlt && sSendMode != SM_PLAY && ctrl_not_down && ctrl_will_not_be_down && !(aModifiersLRunion & (MOD_LSHIFT | MOD_RSHIFT)) // And neither SHIFT key is down, nor will it be. && !(aModifiersLRunion & (MOD_LALT | MOD_RALT)); // And neither ALT key is down, nor will it be. bool release_lwin = (aModifiersLRnow & MOD_LWIN) && !(aModifiersLRnew & MOD_LWIN); bool release_rwin = (aModifiersLRnow & MOD_RWIN) && !(aModifiersLRnew & MOD_RWIN); bool release_lalt = (aModifiersLRnow & MOD_LALT) && !(aModifiersLRnew & MOD_LALT); bool release_ralt = (aModifiersLRnow & MOD_RALT) && !(aModifiersLRnew & MOD_RALT); bool release_lshift = (aModifiersLRnow & MOD_LSHIFT) && !(aModifiersLRnew & MOD_LSHIFT); bool release_rshift = (aModifiersLRnow & MOD_RSHIFT) && !(aModifiersLRnew & MOD_RSHIFT); // Handle ALT and WIN prior to the other modifiers because the "disguise" methods below are // only needed upon release of ALT or WIN. This is because such releases tend to have a better // chance of being "disguised" if SHIFT or CTRL is down at the time of the release. Thus, the // release of SHIFT or CTRL (if called for) is deferred until afterward. // ** WIN // Must be done before ALT in case it is relying on ALT being down to disguise the release WIN. // If ALT is going to be pushed down further below, defer_win_release should be true, which will make sure // the WIN key isn't released until after the ALT key is pushed down here at the top. // Also, WIN is a little more troublesome than ALT, so it is done first in case the ALT key // is down but will be going up, since the ALT key being down might help the WIN key. // For example, if you hold down CTRL, then hold down LWIN long enough for it to auto-repeat, // then release CTRL before releasing LWIN, the Start Menu would appear, at least on XP. // But it does not appear if CTRL is released after LWIN. // Also note that the ALT key can disguise the WIN key, but not vice versa. if (release_lwin) { if (!defer_win_release) { // Fixed for v1.0.25: To avoid triggering the system's LAlt+Shift language hotkey, the // Control key is now used to suppress LWIN/RWIN (preventing the Start Menu from appearing) // rather than the Shift key. This is definitely needed for ALT, but is done here for // WIN also in case ALT is down, which might cause the use of SHIFT as the disguise key // to trigger the language switch. if (ctrl_nor_shift_nor_alt_down && aDisguiseUpWinAlt // Nor will they be pushed down later below, otherwise defer_win_release would have been true and we couldn't get to this point. && sSendMode != SM_PLAY) // SendPlay can't display Start Menu, so disguise not needed (also, disguise might mess up some games). KeyEvent(KEYDOWNANDUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Disguise key release to suppress Start Menu. // The above event is safe because if we're here, it means VK_CONTROL will not be // pressed down further below. In other words, we're not defeating the job // of this function by sending these disguise keystrokes. KeyEvent(KEYUP, VK_LWIN, 0, NULL, false, aExtraInfo); } // else release it only after the normal operation of the function pushes down the disguise keys. } else if (!(aModifiersLRnow & MOD_LWIN) && (aModifiersLRnew & MOD_LWIN)) // Press down LWin. { if (disguise_win_down) KeyEvent(KEYDOWN, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. KeyEvent(KEYDOWN, VK_LWIN, 0, NULL, false, aExtraInfo); if (disguise_win_down) KeyEvent(KEYUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. } if (release_rwin) { if (!defer_win_release) { if (ctrl_nor_shift_nor_alt_down && MOD_RWIN && sSendMode != SM_PLAY) KeyEvent(KEYDOWNANDUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Disguise key release to suppress Start Menu. KeyEvent(KEYUP, VK_RWIN, 0, NULL, false, aExtraInfo); } // else release it only after the normal operation of the function pushes down the disguise keys. } else if (!(aModifiersLRnow & MOD_RWIN) && (aModifiersLRnew & MOD_RWIN)) // Press down RWin. { if (disguise_win_down) KeyEvent(KEYDOWN, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. KeyEvent(KEYDOWN, VK_RWIN, 0, NULL, false, aExtraInfo); if (disguise_win_down) KeyEvent(KEYUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. } // ** SHIFT (PART 1 OF 2) if (release_shift_before_alt_ctrl) { if (release_lshift) KeyEvent(KEYUP, VK_LSHIFT, 0, NULL, false, aExtraInfo); if (release_rshift) KeyEvent(KEYUP, VK_RSHIFT, 0, NULL, false, aExtraInfo); } // ** ALT if (release_lalt) {
tinku99/ahkdll
c2400596508ac5602d9b35048ed489854ac1d069
Fixed Send sleep e.g. Send abc{100}def
diff --git a/source/keyboard_mouse.cpp b/source/keyboard_mouse.cpp index 52aa509..6b1315d 100644 --- a/source/keyboard_mouse.cpp +++ b/source/keyboard_mouse.cpp @@ -1,1152 +1,1155 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 "keyboard_mouse.h" #include "globaldata.h" // for g->KeyDelay #include "application.h" // for MsgSleep() #include "util.h" // for strlicmp() #include "window.h" // for IsWindowHung() // Added for v1.0.25. Search on sPrevEventType for more comments: static KeyEventTypes sPrevEventType; static vk_type sPrevVK = 0; // For v1.0.25, the below is static to track it in between sends, so that the below will continue // to work: // Send {LWinDown} // Send {LWinUp} ; Should still open the Start Menu even though it's a separate Send. static vk_type sPrevEventModifierDown = 0; static modLR_type sModifiersLR_persistent = 0; // Tracks this script's own lifetime/persistent modifiers (the ones it caused to be persistent and thus is responsible for tracking). // v1.0.44.03: Below supports multiple keyboard layouts better by having script adapt to active window's layout. #define MAX_CACHED_LAYOUTS 10 // Hard to imagine anyone using more languages/layouts than this, but even if they do it will still work; performance would just be a little worse due to being uncached. static CachedLayoutType sCachedLayout[MAX_CACHED_LAYOUTS] = {{0}}; static HKL sTargetKeybdLayout; // Set by SendKeys() for use by the functions it calls directly and indirectly. static ResultType sTargetLayoutHasAltGr; // // v1.0.43: Support for SendInput() and journal-playback hook: #define MAX_INITIAL_EVENTS_SI 500UL // sizeof(INPUT) == 28 as of 2006. Since Send is called so often, and since most Sends are short, reducing the load on the stack is also a deciding factor for these. #define MAX_INITIAL_EVENTS_PB 1500UL // sizeof(PlaybackEvent) == 8, so more events are justified before resorting to malloc(). static LPINPUT sEventSI; // No init necessary. An array that's allocated/deallocated by SendKeys(). static PlaybackEvent *&sEventPB = (PlaybackEvent *&)sEventSI; static UINT sEventCount, sMaxEvents; // Number of items in the above arrays and the current array capacity. static UINT sCurrentEvent; static modLR_type sEventModifiersLR; // Tracks the modifier state to following the progress/building of the SendInput array. static POINT sSendInputCursorPos; // Tracks/predicts cursor position as SendInput array is built. #ifndef MINIDLL static HookType sHooksToRemoveDuringSendInput; #endif static SendModes sSendMode = SM_EVENT; // Whether a SendInput or Hook array is currently being constructed. static bool sAbortArraySend; // No init needed. static bool sFirstCallForThisEvent; // static bool sInBlindMode; // static DWORD sThisEventTime; // // Dynamically resolve SendInput() because otherwise the app won't launch at all on Windows 95/NT-pre-SP3: typedef UINT (WINAPI *MySendInputType)(UINT, LPINPUT, int); static MySendInputType sMySendInput = (MySendInputType)GetProcAddress(GetModuleHandle(_T("user32")), "SendInput"); // Above will be NULL for Win95/NT-pre-SP3. void DisguiseWinAltIfNeeded(vk_type aVK) // For v1.0.25, the following situation is fixed by the code below: If LWin or LAlt // becomes a persistent modifier (e.g. via Send {LWin down}) and the user physically // releases LWin immediately before: 1) the {LWin up} is scheduled; and 2) SendKey() // returns. Then SendKey() will push the modifier back down so that it is in effect // for other things done by its caller (SendKeys) and also so that if the Send // operation ends, the key will still be down as the user intended (to modify future // keystrokes, physical or simulated). However, since that down-event is followed // immediately by an up-event, the Start Menu appears for WIN-key or the active // window's menu bar is activated for ALT-key. SOLUTION: Disguise Win-up and Alt-up // events in these cases. This workaround has been successfully tested. It's also // limited is scope so that a script can still explicitly invoke the Start Menu with // "Send {LWin}", or activate the menu bar with "Send {Alt}". // The check of sPrevEventModifierDown allows "Send {LWinDown}{LWinUp}" etc., to // continue to work. // v1.0.40: For maximum flexibility and minimum interference while in blind mode, // don't disguise Win and Alt keystrokes then. { // Caller has ensured that aVK is about to have a key-up event, so if the event immediately // prior to this one is a key-down of the same type of modifier key, it's our job here // to send the disguising keystrokes now (if appropriate). if (sPrevEventType == KEYDOWN && sPrevEventModifierDown != aVK && !sInBlindMode // SendPlay mode can't display Start Menu, so no need for disguise keystrokes (such keystrokes might cause // unwanted effects in certain games): && ((aVK == VK_LWIN || aVK == VK_RWIN) && (sPrevVK == VK_LWIN || sPrevVK == VK_RWIN) && sSendMode != SM_PLAY || (aVK == VK_LMENU || (aVK == VK_RMENU && sTargetLayoutHasAltGr != CONDITION_TRUE)) && (sPrevVK == VK_LMENU || sPrevVK == VK_RMENU))) KeyEvent(KEYDOWNANDUP, g_MenuMaskKey); // Disguise it to suppress Start Menu or prevent activation of active window's menu bar. } // moved from SendKeys void SendUnicodeChar(wchar_t aChar, int aModifiers = -1) { + // Set modifier keystate for consistent results. If not specified by caller, default to releasing + // Alt/Ctrl/Shift since these are known to interfere in some cases, and because SendAsc() does it + // (except for LAlt). Leave LWin/RWin as they are, for consistency with SendAsc(). + if (aModifiers == -1) + { + aModifiers = sSendMode ? sEventModifiersLR : GetModifierLRState(); + aModifiers &= ~(MOD_LALT | MOD_RALT | MOD_LCONTROL | MOD_RCONTROL | MOD_LSHIFT | MOD_RSHIFT); + } + SetModifierLRState((modLR_type)aModifiers, sSendMode ? sEventModifiersLR : GetModifierLRState(), NULL, false, true, KEY_IGNORE); + if (sSendMode == SM_INPUT) { // Calling SendInput() now would cause characters to appear out of sequence. // Instead, put them into the array and allow them to be sent in sequence. PutKeybdEventIntoArray(0, 0, aChar, KEYEVENTF_UNICODE, KEY_IGNORE); PutKeybdEventIntoArray(0, 0, aChar, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, KEY_IGNORE); return; } //else caller has ensured sSendMode is SM_EVENT. In that mode, events are sent one at a time, // so it is safe to immediately call SendInput(). SM_PLAY is not supported; for simplicity, // SendASC() is called instead of this function. Although this means Unicode chars probably // won't work, it seems better than sending chars out of order. One possible alternative could // be to "flush" the event array, but since SendInput and SendEvent are probably much more common, // this is left for a future version. - // Set modifier keystate for consistent results. If not specified by caller, default to releasing - // Alt/Ctrl/Shift since these are known to interfere in some cases, and because SendAsc() does it - // (except for LAlt). Leave LWin/RWin as they are, for consistency with SendAsc(). - if (aModifiers == -1) - { - aModifiers = sSendMode ? sEventModifiersLR : GetModifierLRState(); - aModifiers &= ~(MOD_LALT | MOD_RALT | MOD_LCONTROL | MOD_RCONTROL | MOD_LSHIFT | MOD_RSHIFT); - } - SetModifierLRState((modLR_type)aModifiers, sSendMode ? sEventModifiersLR : GetModifierLRState(), NULL, false, true, KEY_IGNORE); - INPUT u_input[2]; u_input[0].type = INPUT_KEYBOARD; u_input[0].ki.wVk = 0; u_input[0].ki.wScan = aChar; u_input[0].ki.dwFlags = KEYEVENTF_UNICODE; u_input[0].ki.time = 0; // L25: Set dwExtraInfo to ensure AutoHotkey ignores the event; otherwise it may trigger a SCxxx hotkey (where xxx is u_code). u_input[0].ki.dwExtraInfo = KEY_IGNORE; u_input[1].type = INPUT_KEYBOARD; u_input[1].ki.wVk = 0; u_input[1].ki.wScan = aChar; u_input[1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP; u_input[1].ki.time = 0; u_input[1].ki.dwExtraInfo = KEY_IGNORE; SendInput(2, u_input, sizeof(INPUT)); } void SendKeys(LPTSTR aKeys, bool aSendRaw, SendModes aSendModeOrig, HWND aTargetWindow, unsigned int sendahk) // The aKeys string must be modifiable (not constant), since for performance reasons, // it's allowed to be temporarily altered by this function. mThisHotkeyModifiersLR, if non-zero, // should be the set of modifiers used to trigger the hotkey that called the subroutine // containing the Send that got us here. If any of those modifiers are still down, // they will be released prior to sending the batch of keys specified in <aKeys>. // v1.0.43: aSendModeOrig was added. { if (!*aKeys) return; global_struct &g = *::g; // Reduces code size and may improve performance. // For performance and also to reserve future flexibility, recognize {Blind} only when it's the first item // in the string. if (sInBlindMode = !aSendRaw && !_tcsnicmp(aKeys, _T("{Blind}"), 7)) // Don't allow {Blind} while in raw mode due to slight chance {Blind} is intended to be sent as a literal string. // Blind Mode (since this seems too obscure to document, it's mentioned here): Blind Mode relies // on modifiers already down for something like ^c because ^c is saying "manifest a ^c", which will // happen if ctrl is already down. By contrast, Blind does not release shift to produce lowercase // letters because avoiding that adds flexibility that couldn't be achieved otherwise. // Thus, ^c::Send {Blind}c produces the same result when ^c is substituted for the final c. // But Send {Blind}{LControl down} will generate the extra events even if ctrl already down. aKeys += 7; // Remove "{Blind}" from further consideration. int orig_key_delay = g.KeyDelay; int orig_press_duration = g.PressDuration; if (aSendModeOrig == SM_INPUT || aSendModeOrig == SM_INPUT_FALLBACK_TO_PLAY) // Caller has ensured aTargetWindow==NULL for SendInput and SendPlay modes. { // Both of these modes fall back to a different mode depending on whether some other script // is running with a keyboard/mouse hook active. Of course, the detection of this isn't foolproof // because older versions of AHK may be running and/or other apps with LL keyboard hooks. It's // just designed to add a lot of value for typical usage because SendInput is preferred due to it // being considerably faster than SendPlay, especially for long replacements when the CPU is under // heavy load. if ( !sMySendInput // Win95/NT-pre-SP3 don't support SendInput, so fall back to the specified mode. || SystemHasAnotherKeybdHook() // This function has been benchmarked to ensure it doesn't yield our timeslice, etc. 200 calls take 0ms according to tick-count, even when CPU is maxed. || !aSendRaw && SystemHasAnotherMouseHook() && tcscasestr(aKeys, _T("{Click")) ) // Ordered for short-circuit boolean performance. v1.0.43.09: Fixed to be strcasestr vs. !strcasestr { // Need to detect in advance what type of array to build (for performance and code size). That's why // it done this way, and here are the comments about it: // strcasestr() above has an unwanted amount of overhead if aKeys is huge, but it seems acceptable // because it's called only when system has another mouse hook but *not* another keybd hook (very rare). // Also, for performance reasons, {LButton and such are not checked for, which is documented and seems // justified because the new {Click} method is expected to become prevalent, especially since this // whole section only applies when the new SendInput mode is in effect. // Finally, checking aSendRaw isn't foolproof because the string might contain {Raw} prior to {Click, // but the complexity and performance of checking for that seems unjustified given the rarity, // especially since there are almost never any consequences to reverting to hook mode vs. SendInput. if (aSendModeOrig == SM_INPUT_FALLBACK_TO_PLAY) aSendModeOrig = SM_PLAY; else // aSendModeOrig == SM_INPUT, so fall back to EVENT. { aSendModeOrig = SM_EVENT; // v1.0.43.08: When SendInput reverts to SendEvent mode, the majority of users would want // a fast sending rate that is more comparable to SendInput's speed that the default KeyDelay // of 10ms. PressDuration may be generally superior to KeyDelay because it does a delay after // each changing of modifier state (which tends to improve reliability for certain apps). // The following rules seem likely to be the best benefit in terms of speed and reliability: // KeyDelay 0+,-1+ --> -1, 0 // KeyDelay -1, 0+ --> -1, 0 // KeyDelay -1,-1 --> -1, -1 g.PressDuration = (g.KeyDelay < 0 && g.PressDuration < 0) ? -1 : 0; g.KeyDelay = -1; // Above line must be done before this one. } } else // SendInput is available and no other impacting hooks are obviously present on the system, so use SendInput unconditionally. aSendModeOrig = SM_INPUT; // Resolve early so that other sections don't have to consider SM_INPUT_FALLBACK_TO_PLAY a valid value. } // Might be better to do this prior to changing capslock state. UPDATE: In v1.0.44.03, the following section // has been moved to the top of the function because: // 1) For ControlSend, GetModifierLRState() might be more accurate if the threads are attached beforehand. // 2) Determines sTargetKeybdLayout and sTargetLayoutHasAltGr early (for maintainability). bool threads_are_attached = false; // Set default. DWORD keybd_layout_thread = 0; // DWORD target_thread; // Doesn't need init. if (aTargetWindow) // Caller has ensured this is NULL for SendInput and SendPlay modes. { if ((target_thread = GetWindowThreadProcessId(aTargetWindow, NULL)) // Assign. && target_thread != g_MainThreadID && !IsWindowHung(aTargetWindow)) { threads_are_attached = AttachThreadInput(g_MainThreadID, target_thread, TRUE) != 0; keybd_layout_thread = target_thread; // Testing shows that ControlSend benefits from the adapt-to-layout technique too. } //else no target thread, or it's our thread, or it's hung; so keep keybd_layout_thread at its default. } else { // v1.0.48.01: On Vista or later, work around the fact that an "L" keystroke (physical or artificial) will // lock the computer whenever either Windows key is physically pressed down (artificially releasing the // Windows key isn't enough to solve it because Win+L is apparently detected aggressively like // Ctrl-Alt-Delete. Unlike the handling of SM_INPUT in another section, this one here goes into // effect for all Sends because waiting for an "L" keystroke to be sent would be too late since the // Windows would have already been artificially released by then, so IsKeyDownAsync() wouldn't be // able to detect when the user physically releases the key. if ( (g_script.mThisHotkeyModifiersLR & (MOD_LWIN|MOD_RWIN)) // Limit the scope to only those hotkeys that have a Win modifier, since anything outside that scope hasn't been fully analyzed. #ifndef MINIDLL && (GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)50 // Ensure g_script.mThisHotkeyModifiersLR is up-to-date enough to be reliable. #endif && aSendModeOrig == SM_EVENT // SM_INPUT's workaround for Vista is handled by another section. v1.0.48.04: Fixed sSendMode to be aSendModeOrig. && !sInBlindMode // The philosophy of blind-mode is that the script should have full control, so don't do any waiting during blind mode. && g_os.IsWinVistaOrLater() // Only Vista (and presumably later OSes) check the physical state of the Windows key for Win+L. && GetCurrentThreadId() == g_MainThreadID // Exclude the hook thread because it isn't allowed to call anything like MsgSleep, nor are any calls from the hook thread within the understood/analyzed scope of this workaround. ) { bool wait_for_win_key_release; if (aSendRaw) wait_for_win_key_release = StrChrAny(aKeys, _T("Ll")) != NULL; else { // It seems worthwhile to scan for any "L" characters to avoid waiting for the release // of the Windows key when there are no L's. For performance and code size, the check // below isn't comprehensive (e.g. it fails to consider things like {L} and #L). // Although RegExMatch() could be used instead of the below, that would use up one of // the RegEx cache entries, plus it would probably perform worse. So scan manually. LPTSTR L_pos, brace_pos; for (wait_for_win_key_release = false, brace_pos = aKeys; L_pos = StrChrAny(brace_pos, _T("Ll"));) { // Encountering a #L seems too rare, and the consequences too mild (or nonexistent), to // justify the following commented-out section: //if (L_pos > aKeys && L_pos[-1] == '#') // A simple check; it won't detect things like #+L. // brace_pos = L_pos + 1; //else if (!(brace_pos = StrChrAny(L_pos + 1, _T("{}"))) || *brace_pos == '{') // See comment below. { wait_for_win_key_release = true; break; } //else it found a '}' without a preceding '{', which means this "L" is inside braces. // For simplicity, ignore such L's (probably not a perfect check, but seems worthwhile anyway). } } if (wait_for_win_key_release) while (IsKeyDownAsync(VK_LWIN) || IsKeyDownAsync(VK_RWIN)) // Even if the keyboard hook is installed, it seems best to use IsKeyDownAsync() vs. g_PhysicalKeyState[] because it's more likely to produce consistent behavior. SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED); // Seems best not to allow other threads to launch, for maintainability and because SendKeys() isn't designed to be interruptible. } // v1.0.44.03: The following change is meaningful only to people who use more than one keyboard layout. // It seems that the vast majority of them would want the Send command (as well as other features like // Hotstrings and the Input command) to adapt to the keyboard layout of the active window (or target window // in the case of ControlSend) rather than sticking with the script's own keyboard layout. In addition, // testing shows that this adapt-to-layout method costs almost nothing in performance, especially since // the active window, its thread, and its layout are retrieved only once for each Send rather than once // for each keystroke. HWND active_window; if (active_window = GetForegroundWindow()) keybd_layout_thread = GetWindowThreadProcessId(active_window, NULL); //else no foreground window, so keep keybd_layout_thread at default. } #ifdef AHKX sTargetKeybdLayout = g_HKL; // If keybd_layout_thread==0, this will get our thread's own layout, which seems like the best/safest default. sTargetLayoutHasAltGr = LayoutHasAltGr(sTargetKeybdLayout); // Note that WM_INPUTLANGCHANGEREQUEST is not monitored by MsgSleep for the purpose of caching our thread's keyboard layout. This is because it would be unreliable if another msg pump such as MsgBox is running. Plus it hardly helps perf. at all, and hurts maintainability. #else sTargetKeybdLayout = GetKeyboardLayout(keybd_layout_thread); // If keybd_layout_thread==0, this will get our thread's own layout, which seems like the best/safest default. sTargetLayoutHasAltGr = LayoutHasAltGr(sTargetKeybdLayout); // Note that WM_INPUTLANGCHANGEREQUEST is not monitored by MsgSleep for the purpose of caching our thread's keyboard layout. This is because it would be unreliable if another msg pump such as MsgBox is running. Plus it hardly helps perf. at all, and hurts maintainability. #endif // Below is now called with "true" so that the hook's modifier state will be corrected (if necessary) // prior to every send. modLR_type mods_current = GetModifierLRState(true); // Current "logical" modifier state. // Make a best guess of what the physical state of the keys is prior to starting (there's no way // to be certain without the keyboard hook). Note: We only want those physical // keys that are also logically down (it's possible for a key to be down physically // but not logically such as when R-control, for example, is a suffix hotkey and the // user is physically holding it down): modLR_type mods_down_physically_orig, mods_down_physically_and_logically , mods_down_physically_but_not_logically_orig; if (g_KeybdHook) { // Since hook is installed, use its more reliable tracking to determine which // modifiers are down. mods_down_physically_orig = g_modifiersLR_physical; mods_down_physically_and_logically = g_modifiersLR_physical & g_modifiersLR_logical; // intersect mods_down_physically_but_not_logically_orig = g_modifiersLR_physical & ~g_modifiersLR_logical; } else // Use best-guess instead. { // Even if TickCount has wrapped due to system being up more than about 49 days, // DWORD subtraction still gives the right answer as long as g_script.mThisHotkeyStartTime // itself isn't more than about 49 days ago: if ((GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)g_HotkeyModifierTimeout) // Elapsed time < timeout-value mods_down_physically_orig = mods_current & g_script.mThisHotkeyModifiersLR; // Bitwise AND is set intersection. else // Since too much time as passed since the user pressed the hotkey, it seems best, // based on the action that will occur below, to assume that no hotkey modifiers // are physically down: mods_down_physically_orig = 0; mods_down_physically_and_logically = mods_down_physically_orig; mods_down_physically_but_not_logically_orig = 0; // There's no way of knowing, so assume none. } // Any of the external modifiers that are down but NOT due to the hotkey are probably // logically down rather than physically (perhaps from a prior command such as // "Send, {CtrlDown}". Since there's no way to be sure without the keyboard hook or some // driver-level monitoring, it seems best to assume that // they are logically vs. physically down. This value contains the modifiers that // we will not attempt to change (e.g. "Send, A" will not release the LWin // before sending "A" if this value indicates that LWin is down). The below sets // the value to be all the down-keys in mods_current except any that are physically // down due to the hotkey itself. UPDATE: To improve the above, we now exclude from // the set of persistent modifiers any that weren't made persistent by this script. // Such a policy seems likely to do more good than harm as there have been cases where // a modifier was detected as persistent just because #HotkeyModifier had timed out // while the user was still holding down the key, but then when the user released it, // this logic here would think it's still persistent and push it back down again // to enforce it as "always-down" during the send operation. Thus, the key would // basically get stuck down even after the send was over: sModifiersLR_persistent &= mods_current & ~mods_down_physically_and_logically; modLR_type persistent_modifiers_for_this_SendKeys, extra_persistent_modifiers_for_blind_mode; if (sInBlindMode) { // The following value is usually zero unless the user is currently holding down // some modifiers as part of a hotkey. These extra modifiers are the ones that // this send operation (along with all its calls to SendKey and similar) should // consider to be down for the duration of the Send (unless they go up via an // explicit {LWin up}, etc.) extra_persistent_modifiers_for_blind_mode = mods_current & ~sModifiersLR_persistent; persistent_modifiers_for_this_SendKeys = mods_current; } else { extra_persistent_modifiers_for_blind_mode = 0; persistent_modifiers_for_this_SendKeys = sModifiersLR_persistent; } // Above: // Keep sModifiersLR_persistent and persistent_modifiers_for_this_SendKeys in sync with each other from now on. // By contrast to persistent_modifiers_for_this_SendKeys, sModifiersLR_persistent is the lifetime modifiers for // this script that stay in effect between sends. For example, "Send {LAlt down}" leaves the alt key down // even after the Send ends, by design. // // It seems best not to change persistent_modifiers_for_this_SendKeys in response to the user making physical // modifier changes during the course of the Send. This is because it seems more often desirable that a constant // state of modifiers be kept in effect for the entire Send rather than having the user's release of a hotkey // modifier key, which typically occurs at some unpredictable time during the Send, to suddenly alter the nature // of the Send in mid-stride. Another reason is to make the behavior of Send consistent with that of SendInput. // The default behavior is to turn the capslock key off prior to sending any keys // because otherwise lowercase letters would come through as uppercase and vice versa. ToggleValueType prior_capslock_state; if (threads_are_attached || !g_os.IsWin9x()) { // Only under either of the above conditions can the state of Capslock be reliably // retrieved and changed. Remember that apps like MS Word have an auto-correct feature that // might make it wrongly seem that the turning off of Capslock below needs a Sleep(0) to take effect. prior_capslock_state = g.StoreCapslockMode && !sInBlindMode ? ToggleKeyState(VK_CAPITAL, TOGGLED_OFF) : TOGGLE_INVALID; // In blind mode, don't do store capslock (helps remapping and also adds flexibility). } else // OS is Win9x and threads are not attached. { // Attempt to turn off capslock, but never attempt to turn it back on because we can't // reliably detect whether it was on beforehand. Update: This didn't do any good, so // it's disabled for now: //CapslockOffWin9x(); prior_capslock_state = TOGGLE_INVALID; } // sSendMode must be set only after setting Capslock state above, because the hook method // is incapable of changing the on/off state of toggleable keys like Capslock. // However, it can change Capslock state as seen in the window to which playback events are being // sent; but the behavior seems inconsistent and might vary depending on OS type, so it seems best // not to rely on it. sSendMode = aSendModeOrig; if (sSendMode) // Build an array. We're also responsible for setting sSendMode to SM_EVENT prior to returning. { size_t mem_size; if (sSendMode == SM_INPUT) { mem_size = MAX_INITIAL_EVENTS_SI * sizeof(INPUT); sMaxEvents = MAX_INITIAL_EVENTS_SI; } else // Playback type. { mem_size = MAX_INITIAL_EVENTS_PB * sizeof(PlaybackEvent); sMaxEvents = MAX_INITIAL_EVENTS_PB; } // _alloca() is used to avoid the overhead of malloc/free (99% of Sends will thus fit in stack memory). // _alloca() never returns a failure code, it just raises an exception (e.g. stack overflow). InitEventArray(_alloca(mem_size), sMaxEvents, mods_current); } bool blockinput_prev = g_BlockInput; bool do_selective_blockinput = (g_BlockInputMode == TOGGLE_SEND || g_BlockInputMode == TOGGLE_SENDANDMOUSE) && !sSendMode && !aTargetWindow && g_os.IsWinNT4orLater(); if (do_selective_blockinput) Line::ScriptBlockInput(true); // Turn it on unconditionally even if it was on, since Ctrl-Alt-Del might have disabled it. vk_type vk; sc_type sc; modLR_type key_as_modifiersLR = 0; modLR_type mods_for_next_key = 0; // Above: For v1.0.35, it was changed to modLR vs. mod so that AltGr keys such as backslash and '{' // are supported on layouts such as German when sending to apps such as Putty that are fussy about // which ALT key is held down to produce the character. vk_type this_event_modifier_down; size_t key_text_length, key_name_length; TCHAR *end_pos, *space_pos, *next_word, old_char, single_char_string[2]; KeyEventTypes event_type; int repeat_count, click_x, click_y; bool move_offset, key_down_is_persistent; DWORD placeholder; single_char_string[1] = '\0'; // Terminate in advance. LONG_OPERATION_INIT // Needed even for SendInput/Play. for (; *aKeys; ++aKeys, sPrevEventModifierDown = this_event_modifier_down) { this_event_modifier_down = 0; // Set default for this iteration, overridden selectively below. if (!sSendMode) LONG_OPERATION_UPDATE_FOR_SENDKEYS // This does not measurably affect the performance of SendPlay/Event. if (!aSendRaw && _tcschr(_T("^+!#{}"), *aKeys)) { switch (*aKeys) { case '^': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LCONTROL|MOD_RCONTROL))) mods_for_next_key |= MOD_LCONTROL; // else don't add it, because the value of mods_for_next_key may also used to determine // which keys to release after the key to which this modifier applies is sent. // We don't want persistent modifiers to ever be released because that's how // AutoIt2 behaves and it seems like a reasonable standard. continue; case '+': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LSHIFT|MOD_RSHIFT))) mods_for_next_key |= MOD_LSHIFT; continue; case '!': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LALT|MOD_RALT))) mods_for_next_key |= MOD_LALT; continue; case '#': if (g_script.mIsAutoIt2) // Since AutoIt2 ignores these, ignore them if script is in AutoIt2 mode. continue; if (!(persistent_modifiers_for_this_SendKeys & (MOD_LWIN|MOD_RWIN))) mods_for_next_key |= MOD_LWIN; continue; case '}': continue; // Important that these be ignored. Be very careful about changing this, see below. case '{': { if ( !(end_pos = _tcschr(aKeys + 1, '}')) ) // Ignore it and due to rarity, don't reset mods_for_next_key. continue; // This check is relied upon by some things below that assume a '}' is present prior to the terminator. aKeys = omit_leading_whitespace(aKeys + 1); // v1.0.43: Skip leading whitespace inside the braces to be more flexible. if ( !(key_text_length = end_pos - aKeys) ) { if (end_pos[1] == '}') { // The literal string "{}}" has been encountered, which is interpreted as a single "}". ++end_pos; key_text_length = 1; } else if (IS_SPACE_OR_TAB(end_pos[1])) // v1.0.48: Support "{} down}", "{} downtemp}" and "{} up}". { next_word = omit_leading_whitespace(end_pos + 1); if ( !_tcsnicmp(next_word, _T("Down"), 4) // "Down" or "DownTemp" (or likely enough). || !_tcsnicmp(next_word, _T("Up"), 2) ) { if ( !(end_pos = _tcschr(next_word, '}')) ) // See comments at similar section above. continue; key_text_length = end_pos - aKeys; // This result must be non-zero due to the checks above. } else goto brace_case_end; // The loop's ++aKeys will now skip over the '}', ignoring it. } else // Empty braces {} were encountered (or all whitespace, but literal whitespace isn't sent). goto brace_case_end; // The loop's ++aKeys will now skip over the '}', ignoring it. } if (!_tcsnicmp(aKeys, _T("Click"), 5)) { *end_pos = '\0'; // Temporarily terminate the string here to omit the closing brace from consideration below. ParseClickOptions(omit_leading_whitespace(aKeys + 5), click_x, click_y, vk , event_type, repeat_count, move_offset); *end_pos = '}'; // Undo temp termination. if (repeat_count < 1) // Allow {Click 100, 100, 0} to do a mouse-move vs. click (but modifiers like ^{Click..} aren't supported in this case. MouseMove(click_x, click_y, placeholder, g.DefaultMouseSpeed, move_offset); else // Use SendKey because it supports modifiers (e.g. ^{Click}) SendKey requires repeat_count>=1. SendKey(vk, 0, mods_for_next_key, persistent_modifiers_for_this_SendKeys , repeat_count, event_type, 0, aTargetWindow, click_x, click_y, move_offset); goto brace_case_end; // This {} item completely handled, so move on to next. } else if (!_tcsnicmp(aKeys, _T("Raw"), 3)) // This is used by auto-replace hotstrings too. { // As documented, there's no way to switch back to non-raw mode afterward since there's no // correct way to support special (non-literal) strings such as {Raw Off} while in raw mode. aSendRaw = true; goto brace_case_end; // This {} item completely handled, so move on to next. } // Since above didn't "goto", this item isn't {Click}. event_type = KEYDOWNANDUP; // Set defaults. repeat_count = 1; // key_name_length = key_text_length; // *end_pos = '\0'; // Temporarily terminate the string here to omit the closing brace from consideration below. if (space_pos = StrChrAny(aKeys, _T(" \t"))) // Assign. Also, it relies on the fact that {} key names contain no spaces. { old_char = *space_pos; *space_pos = '\0'; // Temporarily terminate here so that TextToVK() can properly resolve a single char. key_name_length = space_pos - aKeys; // Override the default value set above. next_word = omit_leading_whitespace(space_pos + 1); UINT next_word_length = (UINT)(end_pos - next_word); if (next_word_length > 0) { if (!_tcsnicmp(next_word, _T("Down"), 4)) { event_type = KEYDOWN; // v1.0.44.05: Added key_down_is_persistent (which is not initialized except here because // it's only applicable when event_type==KEYDOWN). It avoids the following problem: // When a key is remapped to become a modifier (such as F1::Control), launching one of // the script's own hotkeys via F1 would lead to bad side-effects if that hotkey uses // the Send command. This is because the Send command assumes that any modifiers pressed // down by the script itself (such as Control) are intended to stay down during all // keystrokes generated by that script. To work around this, something like KeyWait F1 // would otherwise be needed. within any hotkey triggered by the F1 key. key_down_is_persistent = _tcsnicmp(next_word + 4, _T("Temp"), 4); // "DownTemp" means non-persistent. } else if (!_tcsicmp(next_word, _T("Up"))) event_type = KEYUP; else repeat_count = ATOI(next_word); // Above: If negative or zero, that is handled further below. // There is no complaint for values <1 to support scripts that want to conditionally send // zero keystrokes, e.g. Send {a %Count%} } } vk = TextToVK(aKeys, &mods_for_next_key, true, false, sTargetKeybdLayout); // false must be passed due to below. sc = vk ? 0 : TextToSC(aKeys); // If sc is 0, it will be resolved by KeyEvent() later. if (!vk && !sc && ctoupper(aKeys[0]) == 'V' && ctoupper(aKeys[1]) == 'K') { LPTSTR sc_string = StrChrAny(aKeys + 2, _T("Ss")); // Look for the "SC" that demarks the scan code. if (sc_string && ctoupper(sc_string[1]) == 'C') sc = (sc_type)_tcstol(sc_string + 2, NULL, 16); // Convert from hex. // else leave sc set to zero and just get the specified VK. This supports Send {VKnn}. vk = (vk_type)_tcstol(aKeys + 2, NULL, 16); // Convert from hex. } if (space_pos) // undo the temporary termination *space_pos = old_char; *end_pos = '}'; // undo the temporary termination if (repeat_count < 1) goto brace_case_end; // Gets rid of one level of indentation. Well worth it. if (vk || sc) { if (key_as_modifiersLR = KeyToModifiersLR(vk, sc)) // Assign { if (!aTargetWindow) { if (event_type == KEYDOWN) // i.e. make {Shift down} have the same effect {ShiftDown} { this_event_modifier_down = vk; if (key_down_is_persistent) // v1.0.44.05. sModifiersLR_persistent |= key_as_modifiersLR; persistent_modifiers_for_this_SendKeys |= key_as_modifiersLR; // v1.0.44.06: Added this line to fix the fact that "DownTemp" should keep the key pressed down after the send. } else if (event_type == KEYUP) // *not* KEYDOWNANDUP, since that would be an intentional activation of the Start Menu or menu bar. { DisguiseWinAltIfNeeded(vk); sModifiersLR_persistent &= ~key_as_modifiersLR; // By contrast with KEYDOWN, KEYUP should also remove this modifier // from extra_persistent_modifiers_for_blind_mode if it happens to be // in there. For example, if "#i::Send {LWin Up}" is a hotkey, // LWin should become persistently up in every respect. extra_persistent_modifiers_for_blind_mode &= ~key_as_modifiersLR; // Fix for v1.0.43: Also remove LControl if this key happens to be AltGr. if (vk == VK_RMENU && sTargetLayoutHasAltGr == CONDITION_TRUE) // It is AltGr. extra_persistent_modifiers_for_blind_mode &= ~MOD_LCONTROL; // Since key_as_modifiersLR isn't 0, update to reflect any changes made above: persistent_modifiers_for_this_SendKeys = sModifiersLR_persistent | extra_persistent_modifiers_for_blind_mode; } // else must never change sModifiersLR_persistent in response to KEYDOWNANDUP // because that would break existing scripts. This is because that same // modifier key may have been pushed down via {ShiftDown} rather than "{Shift Down}". // In other words, {Shift} should never undo the effects of a prior {ShiftDown} // or {Shift down}. } //else don't add this event to sModifiersLR_persistent because it will not be // manifest via keybd_event. Instead, it will done via less intrusively // (less interference with foreground window) via SetKeyboardState() and // PostMessage(). This change is for ControlSend in v1.0.21 and has been // documented. } // Below: sModifiersLR_persistent stays in effect (pressed down) even if the key // being sent includes that same modifier. Surprisingly, this is how AutoIt2 // behaves also, which is good. Example: Send, {AltDown}!f ; this will cause // Alt to still be down after the command is over, even though F is modified // by Alt. SendKey(vk, sc, mods_for_next_key, persistent_modifiers_for_this_SendKeys , repeat_count, event_type, key_as_modifiersLR, aTargetWindow); } else if (isdigit((UCHAR)*aKeys) && key_name_length > 1) { - SLEEP_WITHOUT_INTERRUPTION((int)ATOI(aKeys)); + if (sSendMode != SM_EVENT) // || (sSendMode == SM_INPUT && !SystemHasAnotherKeybdHook())) + PutKeybdEventIntoArray(0, 0, 0, 0,ATOI(aKeys)); + else + SLEEP_WITHOUT_INTERRUPTION(ATOI(aKeys)); } else if (key_name_length == 1) // No vk/sc means a char of length one is sent via special method. { // v1.0.40: SendKeySpecial sends only keybd_event keystrokes, not ControlSend style // keystrokes. // v1.0.43.07: Added check of event_type!=KEYUP, which causes something like Send {ð up} to // do nothing if the curr. keyboard layout lacks such a key. This is relied upon by remappings // such as F1::ð (i.e. a destination key that doesn't have a VK, at least in English). if (event_type != KEYUP) // In this mode, mods_for_next_key and event_type are ignored due to being unsupported. { if (aTargetWindow) // Although MSDN says WM_CHAR uses UTF-16, it seems to really do automatic // translation between ANSI and UTF-16; we rely on this for correct results: PostMessage(aTargetWindow, WM_CHAR, aKeys[0], 0); else SendKeySpecial(aKeys[0], repeat_count); } } // See comment "else must never change sModifiersLR_persistent" above about why // !aTargetWindow is used below: else if (vk = TextToSpecial(aKeys, key_text_length, event_type , persistent_modifiers_for_this_SendKeys, !aTargetWindow)) // Assign. { if (!aTargetWindow) { if (event_type == KEYDOWN) this_event_modifier_down = vk; else // It must be KEYUP because TextToSpecial() never returns KEYDOWNANDUP. DisguiseWinAltIfNeeded(vk); } // Since we're here, repeat_count > 0. // v1.0.42.04: A previous call to SendKey() or SendKeySpecial() might have left modifiers // in the wrong state (e.g. Send +{F1}{ControlDown}). Since modifiers can sometimes affect // each other, make sure they're in the state intended by the user before beginning: SetModifierLRState(persistent_modifiers_for_this_SendKeys , sSendMode ? sEventModifiersLR : GetModifierLRState() , aTargetWindow, false, false); // It also does DoKeyDelay(g->PressDuration). for (int i = 0; i < repeat_count; ++i) { // Don't tell it to save & restore modifiers because special keys like this one // should have maximum flexibility (i.e. nothing extra should be done so that the // user can have more control): if (sendahk) // N11 inject keys not ignored by ahk KeyEvent(event_type, vk, 0, aTargetWindow, true, KEY_NOIGNORE); else KeyEvent(event_type, vk, 0, aTargetWindow, true); if (!sSendMode) LONG_OPERATION_UPDATE_FOR_SENDKEYS } } else if (key_text_length > 4 && !_tcsnicmp(aKeys, _T("ASC "), 4) && !aTargetWindow) // {ASC nnnnn} { // Include the trailing space in "ASC " to increase uniqueness (selectivity). // Also, sending the ASC sequence to window doesn't work, so don't even try: SendASC(omit_leading_whitespace(aKeys + 3)); // Do this only once at the end of the sequence: DoKeyDelay(); // It knows not to do the delay for SM_INPUT. } else if (key_text_length > 2 && !_tcsnicmp(aKeys, _T("U+"), 2)) { // L24: Send a unicode value as shown by Character Map. wchar_t u_code = (wchar_t) _tcstol(aKeys + 2, NULL, 16); if (aTargetWindow) { // Although MSDN says WM_CHAR uses UTF-16, PostMessageA appears to truncate it to 8-bit. // This probably means it does automatic translation between ANSI and UTF-16. Since we // specifically want to send a Unicode character value, use PostMessageW: PostMessageW(aTargetWindow, WM_CHAR, u_code, 0); } else { // Use SendInput in unicode mode if available, otherwise fall back to SendASC. // To know why the following requires sSendMode != SM_PLAY, see SendUnicodeChar. if (sSendMode != SM_PLAY && g_os.IsWin2000orLater()) { SendUnicodeChar(u_code, mods_for_next_key | persistent_modifiers_for_this_SendKeys); } else // Note that this method generally won't work with Unicode characters except { // with specific controls which support it, such as RichEdit (tested on WordPad). TCHAR asc[8]; *asc = '0'; _itot(u_code, asc + 1, 10); SendASC(asc); } } DoKeyDelay(); } //else do nothing since it isn't recognized as any of the above "else if" cases (see below). // If what's between {} is unrecognized, such as {Bogus}, it's safest not to send // the contents literally since that's almost certainly not what the user intended. // In addition, reset the modifiers, since they were intended to apply only to // the key inside {}. Also, the below is done even if repeat-count is zero. brace_case_end: // This label is used to simplify the code without sacrificing performance. aKeys = end_pos; // In prep for aKeys++ done by the loop. mods_for_next_key = 0; continue; } // case '{' } // switch() } // if (!aSendRaw && strchr("^+!#{}", *aKeys)) else // Encountered a character other than ^+!#{} ... or we're in raw mode. { // Best to call this separately, rather than as first arg in SendKey, since it changes the // value of modifiers and the updated value is *not* guaranteed to be passed. // In other words, SendKey(TextToVK(...), modifiers, ...) would often send the old // value for modifiers. single_char_string[0] = *aKeys; // String was pre-terminated earlier. if (vk = TextToVK(single_char_string, &mods_for_next_key, true, true, sTargetKeybdLayout)) // TextToVK() takes no measurable time compared to the amount of time SendKey takes. { if (!sendahk) SendKey(vk, 0, mods_for_next_key, persistent_modifiers_for_this_SendKeys, 1, KEYDOWNANDUP , 0, aTargetWindow); else SendKey(vk, 0, mods_for_next_key, persistent_modifiers_for_this_SendKeys, 1, KEYDOWNANDUP , 0, aTargetWindow, COORD_UNSPECIFIED, COORD_UNSPECIFIED, false, KEY_NOIGNORE); } else // Try to send it by alternate means. { // In this mode, mods_for_next_key is ignored due to being unsupported. if (aTargetWindow) // Although MSDN says WM_CHAR uses UTF-16, it seems to really do automatic // translation between ANSI and UTF-16; we rely on this for correct results: PostMessage(aTargetWindow, WM_CHAR, *aKeys, 0); else SendKeySpecial(*aKeys, 1); } mods_for_next_key = 0; // Safest to reset this regardless of whether a key was sent. } } // for() modLR_type mods_to_set; if (sSendMode) { int final_key_delay = -1; // Set default. if (!sAbortArraySend && sEventCount > 0) // Check for zero events for performance, but more importantly because playback hook will not operate correctly with zero. { // Add more events to the array (prior to sending) to support the following: // Restore the modifiers to match those the user is physically holding down, but do it as *part* // of the single SendInput/Play call. The reasons it's done here as part of the array are: // 1) It avoids the need for #HotkeyModifierTimeout (and it's superior to it) for both SendInput // and SendPlay. // 2) The hook will not be present during the SendInput, nor can it be reinstalled in time to // catch any physical events generated by the user during the Send. Consequently, there is no // known way to reliably detect physical keystate changes. // 3) Changes made to modifier state by SendPlay are seen only by the active window's thread. // Thus, it would be inconsistent and possibly incorrect to adjust global modifier state // after (or during) a SendPlay. // So rather than resorting to #HotkeyModifierTimeout, we can restore the modifiers within the // protection of SendInput/Play's uninterruptibility, allowing the user's buffered keystrokes // (if any) to hit against the correct modifier state when the SendInput/Play completes. // For example, if #c:: is a hotkey and the user releases Win during the SendInput/Play, that // release would hit after SendInput/Play restores Win to the down position, and thus Win would // not be stuck down. Furthermore, if the user didn't release Win, Win would be in the // correct/intended position. // This approach has a few weaknesses (but the strengths appear to outweigh them): // 1) Hitting SendInput's 5000 char limit would omit the tail-end keystrokes, which would mess up // all the assumptions here. But hitting that limit should be very rare, especially since it's // documented and thus scripts will avoid it. // 2) SendInput's assumed uninterruptibility is false if any other app or script has an LL hook // installed. This too is documented, so scripts should generally avoid using SendInput when // they know there are other LL hooks in the system. In any case, there's no known solution // for it, so nothing can be done. mods_to_set = persistent_modifiers_for_this_SendKeys | (sInBlindMode ? 0 : (mods_down_physically_orig & ~mods_down_physically_but_not_logically_orig)); // The last item is usually 0. // Above: When in blind mode, don't restore physical modifiers. This is done to allow a hotkey // such as the following to release Shift: // +space::SendInput/Play {Blind}{Shift up} // Note that SendPlay can make such a change only from the POV of the target window; i.e. it can // release shift as seen by the target window, but not by any other thread; so the shift key would // still be considered to be down for the purpose of firing hotkeys (it can't change global key state // as seen by GetAsyncKeyState). // For more explanation of above, see a similar section for the non-array/old Send below. SetModifierLRState(mods_to_set, sEventModifiersLR, NULL, true, true); // Disguise in case user released or pressed Win/Alt during the Send (seems best to do it even for SendPlay, though it probably needs only Alt, not Win). // mods_to_set is used further below as the set of modifiers that were explicitly put into effect at the tail end of SendInput. SendEventArray(final_key_delay, mods_to_set); } CleanupEventArray(final_key_delay); } else // A non-array send is in effect, so a more elaborate adjustment to logical modifiers is called for. { // Determine (or use best-guess, if necessary) which modifiers are down physically now as opposed // to right before the Send began. modLR_type mods_down_physically; // As compared to mods_down_physically_orig. if (g_KeybdHook) mods_down_physically = g_modifiersLR_physical; else // No hook, so consult g_HotkeyModifierTimeout to make the determination. // Assume that the same modifiers that were phys+logically down before the Send are still // physically down (though not necessarily logically, since the Send may have released them), // but do this only if the timeout period didn't expire (or the user specified that it never // times out; i.e. elapsed time < timeout-value; DWORD subtraction gives the right answer even if // tick-count has wrapped around). mods_down_physically = (g_HotkeyModifierTimeout < 0 // It never times out or... || (GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)g_HotkeyModifierTimeout) // It didn't time out. ? mods_down_physically_orig : 0; // Restore the state of the modifiers to be those the user is physically holding down right now. // Any modifiers that are logically "persistent", as detected upon entrance to this function // (e.g. due to something such as a prior "Send, {LWinDown}"), are also pushed down if they're not already. // Don't press back down the modifiers that were used to trigger this hotkey if there's // any doubt that they're still down, since doing so when they're not physically down // would cause them to be stuck down, which might cause unwanted behavior when the unsuspecting // user resumes typing. // v1.0.42.04: Now that SendKey() is lazy about releasing Ctrl and/or Shift (but not Win/Alt), // the section below also releases Ctrl/Shift if appropriate. See SendKey() for more details. mods_to_set = persistent_modifiers_for_this_SendKeys; // Set default. if (sInBlindMode) // This section is not needed for the array-sending modes because they exploit uninterruptibility to perform a more reliable restoration. { // At the end of a blind-mode send, modifiers are restored differently than normal. One // reason for this is to support the explicit ability for a Send to turn off a hotkey's // modifiers even if the user is still physically holding them down. For example: // #space::Send {LWin up} ; Fails to release it, by design and for backward compatibility. // #space::Send {Blind}{LWin up} ; Succeeds, allowing LWin to be logically up even though it's physically down. modLR_type mods_changed_physically_during_send = mods_down_physically_orig ^ mods_down_physically; // Fix for v1.0.42.04: To prevent keys from getting stuck down, compensate for any modifiers // the user physically pressed or released during the Send (especially those released). // Remove any modifiers physically released during the send so that they don't get pushed back down: mods_to_set &= ~(mods_changed_physically_during_send & mods_down_physically_orig); // Remove those that changed from down to up. // Conversely, add any modifiers newly, physically pressed down during the Send, because in // most cases the user would want such modifiers to be logically down after the Send. // Obsolete comment from v1.0.40: For maximum flexibility and minimum interference while // in blind mode, never restore modifiers to the down position then. mods_to_set |= mods_changed_physically_during_send & mods_down_physically; // Add those that changed from up to down. } else // Regardless of whether the keyboard hook is present, the following formula applies. mods_to_set |= mods_down_physically & ~mods_down_physically_but_not_logically_orig; // The second item is usually 0. // Above takes into account the fact that the user may have pressed and/or released some modifiers // during the Send. // So it includes all keys that are physically down except those that were down physically but not // logically at the *start* of the send operation (since the send operation may have changed the // logical state). In other words, we want to restore the keys to their former logical-down // position to match the fact that the user is still holding them down physically. The // previously-down keys we don't do this for are those that were physically but not logically down, // such as a naked Control key that's used as a suffix without being a prefix. More details: // mods_down_physically_but_not_logically_orig is used to distinguish between the following two cases, // allowing modifiers to be properly restored to the down position when the hook is installed: // 1) A naked modifier key used only as suffix: when the user phys. presses it, it isn't // logically down because the hook suppressed it. // 2) A modifier that is a prefix, that triggers a hotkey via a suffix, and that hotkey sends // that modifier. The modifier will go back up after the SEND, so the key will be physically // down but not logically. // Use KEY_IGNORE_ALL_EXCEPT_MODIFIER to tell the hook to adjust g_modifiersLR_logical_non_ignored // because these keys being put back down match the physical pressing of those same keys by the // user, and we want such modifiers to be taken into account for the purpose of deciding whether // other hotkeys should fire (or the same one again if auto-repeating): // v1.0.42.04: A previous call to SendKey() might have left Shift/Ctrl in the down position // because by procrastinating, extraneous keystrokes in examples such as "Send ABCD" are // eliminated (previously, such that example released the shift key after sending each key, // only to have to press it down again for the next one. For this reason, some modifiers // might get released here in addition to any that need to get pressed down. That's why // SetModifierLRState() is called rather than the old method of pushing keys down only, // never releasing them. // Put the modifiers in mods_to_set into effect. Although "true" is passed to disguise up-events, // there generally shouldn't be any up-events for Alt or Win because SendKey() would have already // released them. One possible exception to this is when the user physically released Alt or Win // during the send (perhaps only during specific sensitive/vulnerable moments). SetModifierLRState(mods_to_set, GetModifierLRState(), aTargetWindow, true, true); // It also does DoKeyDelay(g->PressDuration). } // End of non-array Send. // For peace of mind and because that's how it was tested originally, the following is done // only after adjusting the modifier state above (since that adjustment might be able to // affect the global variables used below in a meaningful way). if (g_KeybdHook) { // Ensure that g_modifiersLR_logical_non_ignored does not contain any down-modifiers // that aren't down in g_modifiersLR_logical. This is done mostly for peace-of-mind, // since there might be ways, via combinations of physical user input and the Send // commands own input (overlap and interference) for one to get out of sync with the // other. The below uses ^ to find the differences between the two, then uses & to // find which are down in non_ignored that aren't in logical, then inverts those bits // in g_modifiersLR_logical_non_ignored, which sets those keys to be in the up position: g_modifiersLR_logical_non_ignored &= ~((g_modifiersLR_logical ^ g_modifiersLR_logical_non_ignored) & g_modifiersLR_logical_non_ignored); } if (prior_capslock_state == TOGGLED_ON) // The current user setting requires us to turn it back on. ToggleKeyState(VK_CAPITAL, TOGGLED_ON); // Might be better to do this after changing capslock state, since having the threads attached // tends to help with updating the global state of keys (perhaps only under Win9x in this case): if (threads_are_attached) AttachThreadInput(g_MainThreadID, target_thread, FALSE); if (do_selective_blockinput && !blockinput_prev) // Turn it back off only if it was off before we started. Line::ScriptBlockInput(false); // v1.0.43.03: Someone reported that when a non-autoreplace hotstring calls us to do its backspacing, the // hotstring's subroutine can execute a command that activates another window owned by the script before // the original window finished receiving its backspaces. Although I can't reproduce it, this behavior // fits with expectations since our thread won't necessarily have a chance to process the incoming // keystrokes before executing the command that comes after SendInput. If those command(s) activate // another of this thread's windows, that window will most likely intercept the keystrokes (assuming // that the message pump dispatches buffered keystrokes to whichever window is active at the time the // message is processed). // This fix does not apply to the SendPlay or SendEvent modes, the former due to the fact that it sleeps // a lot while the playback is running, and the latter due to key-delay and because testing has never shown // a need for it. if (aSendModeOrig == SM_INPUT && GetWindowThreadProcessId(GetForegroundWindow(), NULL) == g_MainThreadID) // GetWindowThreadProcessId() tolerates a NULL hwnd. SLEEP_WITHOUT_INTERRUPTION(-1); // v1.0.43.08: Restore the original thread key-delay values in case above temporarily overrode them. g.KeyDelay = orig_key_delay; g.PressDuration = orig_press_duration; } 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, int aY, bool aMoveOffset, unsigned int sendahk) // Caller has ensured that: 1) vk or sc may be zero, but not both; 2) aRepeatCount > 0. // This function is responsible for first setting the correct state of the modifier keys // (as specified by the caller) before sending the key. After sending, it should put the // modifier keys back to the way they were originally (UPDATE: It does this only for Win/Alt // for the reasons described near the end of this function). { // Caller is now responsible for verifying this: // Avoid changing modifier states and other things if there is nothing to be sent. // Otherwise, menu bar might activated due to ALT keystrokes that don't modify any key, // the Start Menu might appear due to WIN keystrokes that don't modify anything, etc: //if ((!aVK && !aSC) || aRepeatCount < 1) // return; // I thought maybe it might be best not to release unwanted modifier keys that are already down // (perhaps via something like "Send, {altdown}{esc}{altup}"), but that harms the case where // modifier keys are down somehow, unintentionally: The send command wouldn't behave as expected. // e.g. "Send, abc" while the control key is held down by other means, would send ^a^b^c, // possibly dangerous. So it seems best to default to making sure all modifiers are in the // proper down/up position prior to sending any Keybd events. UPDATE: This has been changed // so that only modifiers that were actually used to trigger that hotkey are released during // the send. Other modifiers that are down may be down intentionally, e.g. due to a previous // call to Send such as: Send {ShiftDown}. // UPDATE: It seems best to save the initial state only once, prior to sending the key-group, // because only at the beginning can the original state be determined without having to // save and restore it in each loop iteration. // UPDATE: Not saving and restoring at all anymore, due to interference (side-effects) // caused by the extra keybd events. // The combination of aModifiersLR and aModifiersLRPersistent are the modifier keys that // should be down prior to sending the specified aVK/aSC. aModifiersLR are the modifiers // for this particular aVK keystroke, but aModifiersLRPersistent are the ones that will stay // in pressed down even after it's sent. modLR_type modifiersLR_specified = aModifiersLR | aModifiersLRPersistent; bool vk_is_mouse = IsMouseVK(aVK); // Caller has ensured that VK is non-zero when it wants a mouse click. // v1.0.48.01: On Vista or later, work around the fact that an "L" keystroke (physical or artificial) will // lock the computer whenever either Windows key is physically pressed down (artificially releasing the // Windows key isn't enough to solve it because Win+L is apparently detected aggressively like Ctrl-Alt-Delete). // Must do the following check BEFORE calling anything like SetModifierLRState() because that is likely to defeat // the ability to detect when the user has physically released LWin/RWin. if ( aVK == 'L' // The virtual key of a letter A-Z is the same as the Ascii code of the uppercase letter. && sSendMode == SM_INPUT // SM_EVENT is handled in another section. SM_PLAY is reported to be incapable of locking the computer. && !sInBlindMode // The philosophy of blind-mode is that the script should have full control, so don't do any waiting during blind mode. && !aTargetWindow // i.e. ControlSend (which is incapable of locking the computer). && g_os.IsWinVistaOrLater() // Only Vista (and presumably later OSes) check the physical state of the Windows key for Win+L. && !(modifiersLR_specified & (MOD_LWIN|MOD_RWIN)) // Exclude any #L keystrokes because they are usually intended by the user to lock the computer. && (g_script.mThisHotkeyModifiersLR & (MOD_LWIN|MOD_RWIN)) // Limit the scope to only those hotkeys that have a Win modifier, since anything outside that scope hasn't been fully analyzed. && (GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)50 // Ensure g_script.mThisHotkeyModifiersLR is up-to-date enough to be reliable. && aRepeatCount > 0 //&& aEventType != KEYUP // An up-event without a down-event is unlikely to need this workaround, but due to rarity (and in case it is necessary for up-events) don't check. && GetCurrentThreadId() == g_MainThreadID // Exclude the hook thread because it isn't allowed to call anything like MsgSleep, nor are any calls from the hook thread within the understood/analyzed scope of this workaround. ) while (IsKeyDownAsync(VK_LWIN) || IsKeyDownAsync(VK_RWIN)) // Even if the keyboard hook is installed, it seems best to use IsKeyDownAsync() vs. g_PhysicalKeyState[] because it's more likely to produce consistent behavior. SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED); // Seems best not to allow other threads to launch, for maintainability and because SendKeys() isn't designed to be interruptible. Also, INTERVAL_UNSPECIFIED performs better. // Sleeping indefinitely seems like the lesser evil compared to having it timeout after a few seconds // because having the PC become accidentally locked might have side effects such as the script continuing // to operate while an incorrect/unintended window is active. LONG_OPERATION_INIT for (int i = 0; i < aRepeatCount; ++i) { if (!sSendMode) LONG_OPERATION_UPDATE_FOR_SENDKEYS // This does not measurably affect the performance of SendPlay/Event. // These modifiers above stay in effect for each of these keypresses. // Always on the first iteration, and thereafter only if the send won't be essentially // instantaneous. The modifiers are checked before every key is sent because // if a high repeat-count was specified, the user may have time to release one or more // of the modifier keys that were used to trigger a hotkey. That physical release // will cause a key-up event which will cause the state of the modifiers, as seen // by the system, to change. For example, if user releases control-key during the operation, // some of the D's won't be control-D's: // ^c::Send,^{d 15} // Also: Seems best to do SetModifierLRState() even if Keydelay < 0: // Update: If this key is itself a modifier, don't change the state of the other // modifier keys just for it, since most of the time that is unnecessary and in // some cases, the extra generated keystrokes would cause complications/side-effects. if (!aKeyAsModifiersLR) { // DISGUISE UP: Pass "true" to disguise UP-events on WIN and ALT due to hotkeys such as: // !a::Send test // !a::Send {LButton} // v1.0.40: It seems okay to tell SetModifierLRState to disguise Win/Alt regardless of // whether our caller is in blind mode. This is because our caller already put any extra // blind-mode modifiers into modifiersLR_specified, which prevents any actual need to // disguise anything (only the release of Win/Alt is ever disguised). // DISGUISE DOWN: Pass "false" to avoid disguising DOWN-events on Win and Alt because Win/Alt // will be immediately followed by some key for them to "modify". The exceptions to this are // when aVK is a mouse button (e.g. sending !{LButton} or #{LButton}). But both of those are // so rare that the flexibility of doing exactly what the script specifies seems better than // a possibly unwanted disguising. Also note that hotkeys such as #LButton automatically use // both hooks so that the Start Menu doesn't appear when the Win key is released, so we're // not responsible for that type of disguising here. SetModifierLRState(modifiersLR_specified, sSendMode ? sEventModifiersLR : GetModifierLRState() , aTargetWindow, false, true, KEY_IGNORE); // See keyboard_mouse.h for explanation of KEY_IGNORE. // SetModifierLRState() also does DoKeyDelay(g->PressDuration). } // v1.0.42.04: Mouse clicks are now handled here in the same loop as keystrokes so that the modifiers // will be readjusted (above) if the user presses/releases modifier keys during the mouse clicks. if (vk_is_mouse && !aTargetWindow) MouseClick(aVK, aX, aY, 1, g->DefaultMouseSpeed, aEventType, aMoveOffset); // Above: Since it's rare to send more than one click, it seems best to simplify and reduce code size // by not doing more than one click at a time event when mode is SendInput/Play. else // Sending mouse clicks via ControlSend is not supported, so in that case fall back to the // old method of sending the VK directly (which probably has no effect 99% of the time): { // ahkx N11 send events not ignored by ahk if(!sendahk) KeyEvent(aEventType, aVK, aSC, aTargetWindow, true); else KeyEvent(aEventType, aVK, aSC, aTargetWindow, true, sendahk); } // N11 } // for() [aRepeatCount] // The final iteration by the above loop does a key or mouse delay (KeyEvent and MouseClick do it internally) // prior to us changing the modifiers below. This is a good thing because otherwise the modifiers would // sometimes be released so soon after the keys they modify that the modifiers are not in effect. // This can be seen sometimes when/ ctrl-shift-tabbing back through a multi-tabbed dialog: // The last ^+{tab} might otherwise not take effect because the CTRL key would be released too quickly. // Release any modifiers that were pressed down just for the sake of the above // event (i.e. leave any persistent modifiers pressed down). The caller should // already have verified that aModifiersLR does not contain any of the modifiers // in aModifiersLRPersistent. Also, call GetModifierLRState() again explicitly // rather than trying to use a saved value from above, in case the above itself // changed the value of the modifiers (i.e. aVk/aSC is a modifier). Admittedly, // that would be pretty strange but it seems the most correct thing to do (another // reason is that the user may have pressed or released modifier keys during the // final mouse/key delay that was done above). if (!aKeyAsModifiersLR) // See prior use of this var for explanation. { // It seems best not to use KEY_IGNORE_ALL_EXCEPT_MODIFIER in this case, though there's // a slight chance that a script or two might be broken by not doing so. The chance // is very slight because the only thing KEY_IGNORE_ALL_EXCEPT_MODIFIER would allow is // something like the following example. Note that the hotkey below must be a hook // hotkey (even more rare) because registered hotkeys will still see the logical modifier // state and thus fire regardless of whether g_modifiersLR_logical_non_ignored says that // they shouldn't: // #b::Send, {CtrlDown}{AltDown} // $^!a::MsgBox You pressed the A key after pressing the B key. // In the above, making ^!a a hook hotkey prevents it from working in conjunction with #b. // UPDATE: It seems slightly better to have it be KEY_IGNORE_ALL_EXCEPT_MODIFIER for these reasons: // 1) Persistent modifiers are fairly rare. When they're in effect, it's usually for a reason // and probably a pretty good one and from a user who knows what they're doing. // 2) The condition that g_modifiersLR_logical_non_ignored was added to fix occurs only when // the user physically presses a suffix key (or auto-repeats one by holding it down) // during the course of a SendKeys() operation. Since the persistent modifiers were // (by definition) already in effect prior to the Send, putting them back down for the // purpose of firing hook hotkeys does not seem unreasonable, and may in fact add value. // DISGUISE DOWN: When SetModifierLRState() is called below, it should only release keys, not press // any down (except if the user's physical keystrokes interfered). Therefore, passing true or false // for the disguise-down-events parameter doesn't matter much (but pass "true" in case the user's // keystrokes did interfere in a way that requires a Alt or Win to be pressed back down, because // disguising it seems best). // DISGUISE UP: When SetModifierLRState() is called below, it is passed "false" for disguise-up // to avoid generating unnecessary disguise-keystrokes. They are not needed because if our keystrokes // were modified by either WIN or ALT, the release of the WIN or ALT key will already be disguised due to // its having modified something while it was down. The exceptions to this are when aVK is a mouse button // (e.g. sending !{LButton} or #{LButton}). But both of those are so rare that the flexibility of doing // exactly what the script specifies seems better than a possibly unwanted disguising. // UPDATE for v1.0.42.04: Only release Win and Alt (if appropriate), not Ctrl and Shift, since we know // Win/Alt don't have to be disguised but our caller would have trouble tracking that info or making that // determination. This avoids extra keystrokes, while still procrastinating the release of Ctrl/Shift so // that those can be left down if the caller's next keystroke happens to need them. modLR_type state_now = sSendMode ? sEventModifiersLR : GetModifierLRState(); modLR_type win_alt_to_be_released = ((state_now ^ aModifiersLRPersistent) & state_now) // The modifiers to be released... & (MOD_LWIN|MOD_RWIN|MOD_LALT|MOD_RALT); // ... but restrict them to only Win/Alt. if (win_alt_to_be_released) SetModifierLRState(state_now & ~win_alt_to_be_released , state_now, aTargetWindow, true, false); // It also does DoKeyDelay(g->PressDuration). } } void SendKeySpecial(TCHAR aChar, int aRepeatCount) // Caller must be aware that keystrokes are sent directly (i.e. never to a target window via ControlSend mode). // It must also be aware that the event type KEYDOWNANDUP is always what's used since there's no way // to support anything else. Furthermore, there's no way to support "modifiersLR_for_next_key" such as ^€ // (assuming € is a character for which SendKeySpecial() is required in the current layout). // This function uses some of the same code as SendKey() above, so maintain them together. { // Caller must verify that aRepeatCount > 1. // Avoid changing modifier states and other things if there is nothing to be sent. // Otherwise, menu bar might activated due to ALT keystrokes that don't modify any key, // the Start Menu might appear due to WIN keystrokes that don't modify anything, etc: //if (aRepeatCount < 1) // return; // v1.0.40: This function was heavily simplified because the old method of simulating // characters via dead keys apparently never executed under any keyboard layout. It never // got past the following on the layouts I tested (Russian, German, Danish, Spanish): // if (!send1 && !send2) // Can't simulate aChar. @@ -2306,1025 +2309,1041 @@ void MouseClick(vk_type aVK, int aX, int aY, int aRepeatCount, int aSpeed, KeyEv // (Thanks to Shimanov for this solution.) // // Remaining known limitations: // 1) Title bar buttons are not visibly in a pressed down state when a simulated click-down is sent // to them. // 2) A window that should not be activated, such as AlwaysOnTop+Disabled, is activated anyway // by SetForegroundWindowEx(). Not yet fixed due to its rarity and minimal consequences. // 3) A related problem for which no solution has been discovered (and perhaps it's too obscure // an issue to justify any added code size): If a remapping such as "F1::LButton" is in effect, // pressing and releasing F1 while the cursor is over a script window's title bar will cause the // window to move slightly the next time the mouse is moved. // 4) Clicking one of the script's window's title bar with a key/button that has been remapped to // become the left mouse button sometimes causes the button to get stuck down from the window's // point of view. The reasons are related to those in #1 above. In both #1 and #2, the workaround // is not at fault because it's not in effect then. Instead, the issue is that DefWindowProc enters // a non-msg-pumping loop while it waits for the user to drag-move the window. If instead the user // releases the button without dragging, the loop exits on its own after a 500ms delay or so. // 5) Obscure behavior caused by keyboard's auto-repeat feature: Use a key that's been remapped to // become the left mouse button to click and hold the minimize button of one of the script's windows. // Drag to the left. The window starts moving. This is caused by the fact that the down-click is // suppressed, thus the remap's hotkey subroutine thinks the mouse button is down, thus its // auto-repeat suppression doesn't work and it sends another click. POINT point; GetCursorPos(&point); // Assuming success seems harmless. // Despite what MSDN says, WindowFromPoint() appears to fetch a non-NULL value even when the // mouse is hovering over a disabled control (at least on XP). HWND child_under_cursor, parent_under_cursor; if ( (child_under_cursor = WindowFromPoint(point)) && (parent_under_cursor = GetNonChildParent(child_under_cursor)) // WM_NCHITTEST below probably requires parent vs. child. && GetWindowThreadProcessId(parent_under_cursor, NULL) == g_MainThreadID ) // It's one of our thread's windows. { LRESULT hit_test = SendMessage(parent_under_cursor, WM_NCHITTEST, 0, MAKELPARAM(point.x, point.y)); if ( aVK == VK_LBUTTON && (hit_test == HTCLOSE || hit_test == HTMAXBUTTON // Title bar buttons: Close, Maximize. || hit_test == HTMINBUTTON || hit_test == HTHELP) // Title bar buttons: Minimize, Help. || aVK == VK_RBUTTON && (hit_test == HTCAPTION || hit_test == HTSYSMENU) ) { if (aEventType == KEYDOWN) { // Ignore this event and substitute for it: Activate the window when one // of its title bar buttons is down-clicked. sWorkaroundVK = aVK; sWorkaroundHitTest = hit_test; SetForegroundWindowEx(parent_under_cursor); // Try to reproduce customary behavior. // For simplicity, aRepeatCount>1 is ignored and DoMouseDelay() is not done. return; } else // KEYUP { if (sWorkaroundHitTest == hit_test) // To weed out cases where user clicked down on a button then released somewhere other than the button. aEventType = KEYDOWNANDUP; // Translate this click-up into down+up to make up for the fact that the down was previously suppressed. //else let the click-up occur in case it does something or user wants it. } } } // Work-around for sending mouse clicks to one of our thread's own windows. } // sWorkaroundVK is reset later below. // Since above didn't return, the work-around isn't in effect and normal click(s) will be sent: if (aVK == VK_LBUTTON) { event_down = MOUSEEVENTF_LEFTDOWN; event_up = MOUSEEVENTF_LEFTUP; } else // aVK == VK_RBUTTON { event_down = MOUSEEVENTF_RIGHTDOWN; event_up = MOUSEEVENTF_RIGHTUP; } break; case VK_MBUTTON: event_down = MOUSEEVENTF_MIDDLEDOWN; event_up = MOUSEEVENTF_MIDDLEUP; break; case VK_XBUTTON1: case VK_XBUTTON2: event_down = MOUSEEVENTF_XDOWN; event_up = MOUSEEVENTF_XUP; event_data = (aVK == VK_XBUTTON1) ? XBUTTON1 : XBUTTON2; break; } // switch() // For simplicity and possibly backward compatibility, LONG_OPERATION_INIT/UPDATE isn't done. // In addition, some callers might do it for themselves, at least when aRepeatCount==1. for (int i = 0; i < aRepeatCount; ++i) { if (aEventType != KEYUP) // It's either KEYDOWN or KEYDOWNANDUP. { // v1.0.43: Reliability is significantly improved by specifying the coordinates with the event (if // caller gave us coordinates). This is mostly because of SetMouseDelay: In previously versions, // the delay between a MouseClick's move and its click allowed time for the user to move the mouse // away from the target position before the click was sent. MouseEvent(event_flags | event_down, event_data, aX, aY); // It ignores aX and aY when MOUSEEVENTF_MOVE is absent. // It seems best to always Sleep a certain minimum time between events // because the click-down event may cause the target app to do something which // changes the context or nature of the click-up event. AutoIt3 has also been // revised to do this. v1.0.40.02: Avoid doing the Sleep between the down and up // events when the workaround is in effect because any MouseDelay greater than 10 // would cause DoMouseDelay() to pump messages, which would defeat the workaround: if (!sWorkaroundVK) DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. } if (aEventType != KEYDOWN) // It's either KEYUP or KEYDOWNANDUP. { MouseEvent(event_flags | event_up, event_data, aX, aY); // It ignores aX and aY when MOUSEEVENTF_MOVE is absent. // It seems best to always do this one too in case the script line that caused // us to be called here is followed immediately by another script line which // is either another mouse click or something that relies upon the mouse click // having been completed: DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. } } // for() sWorkaroundVK = 0; // Reset this indicator in all cases except those for which above already returned. } void MouseMove(int &aX, int &aY, DWORD &aEventFlags, int aSpeed, bool aMoveOffset) // This function also does DoMouseDelay() for the caller. // This function converts aX and aY for the caller into MOUSEEVENTF_ABSOLUTE coordinates. // The exception is when the playback mode is in effect, in which case such a conversion would be undesirable // both here and by the caller. // It also puts appropriate bit-flags into aEventFlags. { // Most callers have already validated this, but some haven't. Since it doesn't take too long to check, // do it here rather than requiring all callers to do (helps maintainability). if (aX == COORD_UNSPECIFIED || aY == COORD_UNSPECIFIED) return; if (sSendMode == SM_PLAY) // Journal playback mode. { // Mouse speed (aSpeed) is ignored for SendInput/Play mode: the mouse always moves instantaneously // (though in the case of playback-mode, MouseDelay still applies between each movement and click). // Playback-mode ignores mouse speed because the cases where the user would want to move the mouse more // slowly (such as a demo) seem too rare to justify the code size and complexity, especially since the // incremental-move code would have to be implemented in the hook itself to ensure reliability. This is // because calling GetCursorPos() before playback begins could cause the mouse to wind up at the wrong // destination, especially if our thread is preempted while building the array (which would give the user // a chance to physically move the mouse before uninterruptibility begins). // For creating demonstrations that user slower mouse movement, the older MouseMove command can be used // in conjunction with BlockInput. This also applies to SendInput because it's conceivable that mouse // speed could be supported there (though it seems useless both visually and to improve reliability // because no mouse delays are possible within SendInput). // // MSG_OFFSET_MOUSE_MOVE is used to have the playback hook apply the offset (rather than doing it here // like is done for SendInput mode). This adds flexibility in cases where a new window becomes active // during playback, or the active window changes position -- if that were to happen, the offset would // otherwise be wrong while CoordMode is Relative because the changes can only be observed and // compensated for during playback. PutMouseEventIntoArray(MOUSEEVENTF_MOVE | (aMoveOffset ? MSG_OFFSET_MOUSE_MOVE : 0) , 0, aX, aY); // The playback hook uses normal vs. MOUSEEVENTF_ABSOLUTE coordinates. DoMouseDelay(); if (aMoveOffset) { // Now that we're done using the old values of aX and aY above, reset them to COORD_UNSPECIFIED // for the caller so that any subsequent clicks it does will be marked as "at current coordinates". aX = COORD_UNSPECIFIED; aY = COORD_UNSPECIFIED; } return; // Other parts below rely on this returning early to avoid converting aX/aY into MOUSEEVENTF_ABSOLUTE. } // The playback mode returned from above doesn't need these flags added because they're ignored for clicks: aEventFlags |= MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; // Done here for caller, for easier maintenance. POINT cursor_pos; if (aMoveOffset) // We're moving the mouse cursor relative to its current position. { if (sSendMode == SM_INPUT) { // Since GetCursorPos() can't be called to find out a future cursor position, use the position // tracked for SendInput (facilitates MouseClickDrag's R-option as well as Send{Click}'s). if (sSendInputCursorPos.x == COORD_UNSPECIFIED) // Initial/starting value hasn't yet been set. GetCursorPos(&sSendInputCursorPos); // Start it off where the cursor is now. aX += sSendInputCursorPos.x; aY += sSendInputCursorPos.y; } else { GetCursorPos(&cursor_pos); // None of this is done for playback mode since that mode already returned higher above. aX += cursor_pos.x; aY += cursor_pos.y; } } else { // Convert relative coords to screen coords if necessary (depends on CoordMode). // None of this is done for playback mode since that mode already returned higher above. CoordToScreen(aX, aY, COORD_MODE_MOUSE); } if (sSendMode == SM_INPUT) // Track predicted cursor position for use by subsequent events put into the array. { sSendInputCursorPos.x = aX; // Always stores normal coords (non-MOUSEEVENTF_ABSOLUTE). sSendInputCursorPos.y = aY; // } // Find dimensions of primary monitor. // Without the MOUSEEVENTF_VIRTUALDESK flag (supported only by SendInput, and then only on // Windows 2000/XP or later), MOUSEEVENTF_ABSOLUTE coordinates are relative to the primary monitor. int screen_width = GetSystemMetrics(SM_CXSCREEN); int screen_height = GetSystemMetrics(SM_CYSCREEN); // Convert the specified screen coordinates to mouse event coordinates (MOUSEEVENTF_ABSOLUTE). // MSDN: "In a multimonitor system, [MOUSEEVENTF_ABSOLUTE] coordinates map to the primary monitor." // The above implies that values greater than 65535 or less than 0 are appropriate, but only on // multi-monitor systems. For simplicity, performance, and backward compatibility, no check for // multi-monitor is done here. Instead, the system's default handling for out-of-bounds coordinates // is used; for example, mouse_event() stops the cursor at the edge of the screen. // UPDATE: In v1.0.43, the following formula was fixed (actually broken, see below) to always yield an // in-range value. The previous formula had a +1 at the end: // aX|Y = ((65535 * aX|Y) / (screen_width|height - 1)) + 1; // The extra +1 would produce 65536 (an out-of-range value for a single-monitor system) if the maximum // X or Y coordinate was input (e.g. x-position 1023 on a 1024x768 screen). Although this correction // seems inconsequential on single-monitor systems, it may fix certain misbehaviors that have been reported // on multi-monitor systems. Update: according to someone I asked to test it, it didn't fix anything on // multimonitor systems, at least those whose monitors vary in size to each other. In such cases, he said // that only SendPlay or DllCall("SetCursorPos") make mouse movement work properly. // FIX for v1.0.44: Although there's no explanation yet, the v1.0.43 formula is wrong and the one prior // to it was correct; i.e. unless +1 is present below, a mouse movement to coords near the upper-left corner of // the screen is typically off by one pixel (only the y-coordinate is affected in 1024x768 resolution, but // in other resolutions both might be affected). // v1.0.44.07: The following old formula has been replaced: // (((65535 * coord) / (width_or_height - 1)) + 1) // ... with the new one below. This is based on numEric's research, which indicates that mouse_event() // uses the following inverse formula internally: // x_or_y_coord = (x_or_y_abs_coord * screen_width_or_height) / 65536 #define MOUSE_COORD_TO_ABS(coord, width_or_height) (((65536 * coord) / width_or_height) + (coord < 0 ? -1 : 1)) aX = MOUSE_COORD_TO_ABS(aX, screen_width); aY = MOUSE_COORD_TO_ABS(aY, screen_height); // aX and aY MUST BE SET UNCONDITIONALLY because the output parameters must be updated for caller. // The incremental-move section further below also needs it. if (aSpeed < 0) // This can happen during script's runtime due to something like: MouseMove, X, Y, %VarContainingNegative% aSpeed = 0; // 0 is the fastest. else if (aSpeed > MAX_MOUSE_SPEED) aSpeed = MAX_MOUSE_SPEED; if (aSpeed == 0 || sSendMode == SM_INPUT) // Instantaneous move to destination coordinates with no incremental positions in between. { // See the comments in the playback-mode section at the top of this function for why SM_INPUT ignores aSpeed. MouseEvent(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, 0, aX, aY); DoMouseDelay(); // Inserts delay for all modes except SendInput, for which it does nothing. return; } // Since above didn't return, use the incremental mouse move to gradually move the cursor until // it arrives at the destination coordinates. // Convert the cursor's current position to mouse event coordinates (MOUSEEVENTF_ABSOLUTE). GetCursorPos(&cursor_pos); DoIncrementalMouseMove( MOUSE_COORD_TO_ABS(cursor_pos.x, screen_width) // Source/starting coords. , MOUSE_COORD_TO_ABS(cursor_pos.y, screen_height) // , aX, aY, aSpeed); // Destination/ending coords. } void MouseEvent(DWORD aEventFlags, DWORD aData, DWORD aX, DWORD aY) // Having this part outsourced to a function helps remember to use KEY_IGNORE so that our own mouse // events won't be falsely detected as hotkeys by the hooks (if they are installed). { if (sSendMode) PutMouseEventIntoArray(aEventFlags, aData, aX, aY); else mouse_event(aEventFlags , aX == COORD_UNSPECIFIED ? 0 : aX // v1.0.43.01: Must be zero if no change in position is desired , aY == COORD_UNSPECIFIED ? 0 : aY // (fixes compatibility with certain apps/games). , aData, KEY_IGNORE); } /////////////////////// // SUPPORT FUNCTIONS // /////////////////////// void PutKeybdEventIntoArray(modLR_type aKeyAsModifiersLR, vk_type aVK, sc_type aSC, DWORD aEventFlags, DWORD aExtraInfo) // This function is designed to be called from only one thread (the main thread) since it's not thread-safe. // Playback hook only supports sending neutral modifiers. Caller must ensure that any left/right modifiers // such as VK_RCONTROL are translated into neutral (e.g. VK_CONTROL). { bool key_up = aEventFlags & KEYEVENTF_KEYUP; // To make the SendPlay method identical in output to the other keystroke methods, have it generate // a leading down/up LControl event immediately prior to each RAlt event (with no key-delay). // This avoids having to add special handling to places like SetModifierLRState() to do AltGr things // differently when sending via playback vs. other methods. The event order recorded by the journal // record hook is a little different than what the low-level keyboard hook sees, but I don't think // the order should matter in this case: // sc vk key msg // 138 12 Alt syskeydown (right vs. left scan code) // 01d 11 Ctrl keydown (left scan code) <-- In keyboard hook, normally this precedes Alt, not follows it. Seems inconsequential (testing confirms). // 01d 11 Ctrl keyup (left scan code) // 138 12 Alt syskeyup (right vs. left scan code) // Check for VK_MENU not VK_RMENU because caller should have translated it to neutral: if (aVK == VK_MENU && aSC == SC_RALT && sTargetLayoutHasAltGr == CONDITION_TRUE && sSendMode == SM_PLAY) // Must pass VK_CONTROL rather than VK_LCONTROL because playback hook requires neutral modifiers. PutKeybdEventIntoArray(MOD_LCONTROL, VK_CONTROL, SC_LCONTROL, aEventFlags, aExtraInfo); // Recursive call to self. // Above must be done prior to the capacity check below because above might add a new array item. if (sEventCount == sMaxEvents) // Array's capacity needs expanding. if (!ExpandEventArray()) return; // Keep track of the predicted modifier state for use in other places: if (key_up) sEventModifiersLR &= ~aKeyAsModifiersLR; else sEventModifiersLR |= aKeyAsModifiersLR; if (sSendMode == SM_INPUT) { INPUT &this_event = sEventSI[sEventCount]; // For performance and convenience. this_event.type = INPUT_KEYBOARD; this_event.ki.wVk = aVK; this_event.ki.wScan = (aEventFlags & KEYEVENTF_UNICODE) ? aSC : LOBYTE(aSC); this_event.ki.dwFlags = aEventFlags; this_event.ki.dwExtraInfo = aExtraInfo; // Although our hook won't be installed (or won't detect, in the case of playback), that of other scripts might be, so set this for them. this_event.ki.time = 0; // Let the system provide its own timestamp, which might be more accurate for individual events if this will be a very long SendInput. #ifndef MINIDLL sHooksToRemoveDuringSendInput |= HOOK_KEYBD; // Presence of keyboard hook defeats uninterruptibility of keystrokes. #endif } else // Playback hook. { PlaybackEvent &this_event = sEventPB[sEventCount]; // For performance and convenience. if (!(aVK || aSC)) // Caller is signaling that aExtraInfo contains a delay/sleep event. { // Although delays at the tail end of the playback array can't be implemented by the playback // itself, caller wants them put in too. this_event.message = 0; // Message number zero flags it as a delay rather than an actual event. this_event.time_to_wait = aExtraInfo; } else // A normal (non-delay) event for playback. { // By monitoring incoming events in a message/event loop, the following key combinations were // confirmed to be WM_SYSKEYDOWN vs. WM_KEYDOWN (up events weren't tested, so are assumed to // be the same as down-events): // Alt+Win // Alt+Shift // Alt+Capslock/Numlock/Scrolllock // Alt+AppsKey // Alt+F2/Delete/Home/End/Arrow/BS // Alt+Space/Enter // Alt+Numpad (tested all digits & most other keys, with/without Numlock ON) // F10 (by itself) / Win+F10 / Alt+F10 / Shift+F10 (but not Ctrl+F10) // By contrast, the following are not SYS: Alt+Ctrl, Alt+Esc, Alt+Tab (the latter two // are never received by msg/event loop probably because the system intercepts them). // So the rule appears to be: It's a normal (non-sys) key if Alt isn't down and the key // isn't F10, or if Ctrl is down. Though a press of the Alt key itself is a syskey unless Ctrl is down. // Update: The release of ALT is WM_KEYUP vs. WM_SYSKEYUP when it modified at least one key while it was down. if (sEventModifiersLR & (MOD_LCONTROL | MOD_RCONTROL) // Control is down... || !(sEventModifiersLR & (MOD_LALT | MOD_RALT)) // ... or: Alt isn't down and this key isn't Alt or F10... && aVK != VK_F10 && !(aKeyAsModifiersLR & (MOD_LALT | MOD_RALT)) || (sEventModifiersLR & (MOD_LALT | MOD_RALT)) && key_up) // ... or this is the release of Alt (for simplicity, assume that Alt modified something while it was down). this_event.message = key_up ? WM_KEYUP : WM_KEYDOWN; else this_event.message = key_up ? WM_SYSKEYUP : WM_SYSKEYDOWN; this_event.vk = aVK; this_event.sc = aSC; // Don't omit the extended-key-bit because it is used later on. } } ++sEventCount; } void PutMouseEventIntoArray(DWORD aEventFlags, DWORD aData, DWORD aX, DWORD aY) // This function is designed to be called from only one thread (the main thread) since it's not thread-safe. // If the array-type is journal playback, caller should include MOUSEEVENTF_ABSOLUTE in aEventFlags if the // the mouse coordinates aX and aY are relative to the screen rather than the active window. { if (sEventCount == sMaxEvents) // Array's capacity needs expanding. if (!ExpandEventArray()) return; if (sSendMode == SM_INPUT) { INPUT &this_event = sEventSI[sEventCount]; // For performance and convenience. this_event.type = INPUT_MOUSE; this_event.mi.dx = (aX == COORD_UNSPECIFIED) ? 0 : aX; // v1.0.43.01: Must be zero if no change in position is this_event.mi.dy = (aY == COORD_UNSPECIFIED) ? 0 : aY; // desired (fixes compatibility with certain apps/games). this_event.mi.dwFlags = aEventFlags; this_event.mi.mouseData = aData; this_event.mi.dwExtraInfo = KEY_IGNORE; // Although our hook won't be installed (or won't detect, in the case of playback), that of other scripts might be, so set this for them. this_event.mi.time = 0; // Let the system provide its own timestamp, which might be more accurate for individual events if this will be a very long SendInput. #ifndef MINIDLL sHooksToRemoveDuringSendInput |= HOOK_MOUSE; // Presence of mouse hook defeats uninterruptibility of mouse clicks/moves. #endif } else // Playback hook. { // Note: Delay events (sleeps), which are supported in playback mode but not SendInput, are always inserted // via PutKeybdEventIntoArray() rather than this function. PlaybackEvent &this_event = sEventPB[sEventCount]; // For performance and convenience. // Determine the type of event specified by caller, but also omit MOUSEEVENTF_MOVE so that the // follow variations can be differentiated: // 1) MOUSEEVENTF_MOVE by itself. // 2) MOUSEEVENTF_MOVE with a click event or wheel turn (in this case MOUSEEVENTF_MOVE is permitted but // not required, since all mouse events in playback mode must have explicit coordinates at the // time they're played back). // 3) A click event or wheel turn by itself (same remark as above). // Bits are isolated in what should be a future-proof way (also omits MSG_OFFSET_MOUSE_MOVE bit). switch (aEventFlags & (0x1FFF & ~MOUSEEVENTF_MOVE)) // v1.0.48: 0x1FFF vs. 0xFFF to support MOUSEEVENTF_HWHEEL. { case 0: this_event.message = WM_MOUSEMOVE; break; // It's a movement without a click. // In cases other than the above, it's a click or wheel turn with optional WM_MOUSEMOVE too. case MOUSEEVENTF_LEFTDOWN: this_event.message = WM_LBUTTONDOWN; break; case MOUSEEVENTF_LEFTUP: this_event.message = WM_LBUTTONUP; break; case MOUSEEVENTF_RIGHTDOWN: this_event.message = WM_RBUTTONDOWN; break; case MOUSEEVENTF_RIGHTUP: this_event.message = WM_RBUTTONUP; break; case MOUSEEVENTF_MIDDLEDOWN: this_event.message = WM_MBUTTONDOWN; break; case MOUSEEVENTF_MIDDLEUP: this_event.message = WM_MBUTTONUP; break; case MOUSEEVENTF_XDOWN: this_event.message = WM_XBUTTONDOWN; break; case MOUSEEVENTF_XUP: this_event.message = WM_XBUTTONUP; break; case MOUSEEVENTF_WHEEL: this_event.message = WM_MOUSEWHEEL; break; case MOUSEEVENTF_HWHEEL: this_event.message = WM_MOUSEHWHEEL; break; // v1.0.48 // WHEEL: No info comes into journal-record about which direction the wheel was turned (nor by how many // notches). In addition, it appears impossible to specify such info when playing back the event. // Therefore, playback usually produces downward wheel movement (but upward in some apps like // Visual Studio). } // COORD_UNSPECIFIED_SHORT is used so that the very first event can be a click with unspecified // coordinates: it seems best to have the cursor's position fetched during playback rather than // here because if done here, there might be time for the cursor to move physically before // playback begins (especially if our thread is preempted while building the array). this_event.x = (aX == COORD_UNSPECIFIED) ? COORD_UNSPECIFIED_SHORT : (WORD)aX; this_event.y = (aY == COORD_UNSPECIFIED) ? COORD_UNSPECIFIED_SHORT : (WORD)aY; if (aEventFlags & MSG_OFFSET_MOUSE_MOVE) // Caller wants this event marked as a movement relative to cursor's current position. this_event.message |= MSG_OFFSET_MOUSE_MOVE; } ++sEventCount; } ResultType ExpandEventArray() // Returns OK or FAIL. { #define EVENT_EXPANSION_MULTIPLIER 2 // Should be very rare for array to need to expand more than a few times. size_t event_size = (sSendMode == SM_INPUT) ? sizeof(INPUT) : sizeof(PlaybackEvent); void *new_mem; // SendInput() appears to be limited to 5000 chars (10000 events in array), at least on XP. This is // either an undocumented SendInput limit or perhaps it's due to the system setting that determines // how many messages can get backlogged in each thread's msg queue before some start to get dropped. // Note that SendInput()'s return value always seems to indicate that all the characters were sent // even when the ones beyond the limit were clearly never received by the target window. // In any case, it seems best not to restrict to 5000 here in case the limit can vary for any reason. // The 5000 limit is documented in the help file. if ( !(new_mem = malloc(EVENT_EXPANSION_MULTIPLIER * sMaxEvents * event_size)) ) sAbortArraySend = true; // Usually better to send nothing rather than partial. // And continue on below to free the old block, if appropriate. else // Copy old array into new memory area (note that sEventSI and sEventPB are different views of the same variable). memcpy(new_mem, sEventSI, sEventCount * event_size); if (sMaxEvents > (sSendMode == SM_INPUT ? MAX_INITIAL_EVENTS_SI : MAX_INITIAL_EVENTS_PB)) free(sEventSI); // Previous block was malloc'd vs. _alloc'd, so free it. if (sAbortArraySend) return FAIL; sEventSI = (LPINPUT)new_mem; // Note that sEventSI and sEventPB are different views of the same variable. sMaxEvents *= EVENT_EXPANSION_MULTIPLIER; return OK; } void InitEventArray(void *aMem, UINT aMaxEvents, modLR_type aModifiersLR) { sEventPB = (PlaybackEvent *)aMem; // Sets sEventSI too, since both are the same. sMaxEvents = aMaxEvents; sEventModifiersLR = aModifiersLR; sSendInputCursorPos.x = COORD_UNSPECIFIED; sSendInputCursorPos.y = COORD_UNSPECIFIED; #ifndef MINIDLL sHooksToRemoveDuringSendInput = 0; #endif sEventCount = 0; sAbortArraySend = false; // If KeyEvent() ever sets it to true, that allows us to send nothing at all rather than a partial send. sFirstCallForThisEvent = true; // The above isn't a local static inside PlaybackProc because PlaybackProc might get aborted in the // middle of a NEXT/SKIP pair by user pressing Ctrl-Esc, etc, which would make it unreliable. } void SendEventArray(int &aFinalKeyDelay, modLR_type aModsDuringSend) // Caller must avoid calling this function if sMySendInput is NULL. // aFinalKeyDelay (which the caller should have initialized to -1 prior to calling) may be changed here // to the desired/final delay. Caller must not act upon it until changing sTypeOfHookToBuild to something // that will allow DoKeyDelay() to do a real delay. { if (sSendMode == SM_INPUT) { // Remove hook(s) temporarily because the presence of low-level (LL) keybd hook completely disables // the uninterruptibility of SendInput's keystrokes (but the mouse hook doesn't affect them). // The converse is also true. This was tested via: // #space:: // SendInput {Click 400, 400, 100} // MsgBox // ExitApp // ... and also with BurnK6 running, a CPU maxing utility. The mouse clicks were sent directly to the // BurnK6 window, and were pretty slow, and also I could physically move the mouse cursor a little // between each of sendinput's mouse clicks. But removing the mouse-hook during SendInputs solves all that. // Rather than removing both hooks unconditionally, it's better to // remove only those that actually have corresponding events in the array. This avoids temporarily // losing visibility of physical key states (especially when the keyboard hook is removed). #ifndef MINIDLL HookType active_hooks; if (active_hooks = GetActiveHooks()) AddRemoveHooks(active_hooks & ~sHooksToRemoveDuringSendInput, true); #endif // Caller has ensured that sMySendInput isn't NULL. - sMySendInput(sEventCount, sEventSI, sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. + // Following is done to support Sleep in Send e.g. Send, abc{100}def + unsigned int aLastEventCount = 0; + for (unsigned int i = 0;i <= sEventCount;i++) + { + // wVK and wScan are 0 and dwExtraInfo holds time to sleep + if (sEventSI[i].ki.wVk == 0 && sEventSI[i].ki.wScan == 0) + { + sMySendInput(i - aLastEventCount, &sEventSI[aLastEventCount], sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. + SLEEP_WITHOUT_INTERRUPTION((int)sEventSI[i].ki.dwExtraInfo); + aLastEventCount = i + 1; // + 1 to skip current item + } + } + // Process unprocessed Events + if (aLastEventCount == 0) + sMySendInput(sEventCount, sEventSI, sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. + else + sMySendInput(aLastEventCount, &sEventSI[aLastEventCount], sizeof(INPUT)); // Must call dynamically-resolved version for Win95/NT compatibility. // The return value is ignored because it never seems to be anything other than sEventCount, even if // the Send seems to partially fail (e.g. due to hitting 5000 event maximum). // Typical speed of SendInput: 10ms or less for short sends (under 100 events). // Typically 30ms for 500 events; and typically no more than 200ms for 5000 events (which is // the apparent max). // Testing shows that when SendInput returns to its caller, all of its key states are in effect // even if the target window hasn't yet had time to receive them all. For example, the // following reports that LShift is down: // SendInput {a 4900}{LShift down} // MsgBox % GetKeyState("LShift") // Furthermore, if the user manages to physically press or release a key during the call to // SendInput, testing shows that such events are in effect immediately when SendInput returns // to its caller, perhaps because SendInput clears out any backlog of physical keystrokes prior to // returning, or perhaps because the part of the OS that updates key states is a very high priority. #ifndef MINIDLL if (active_hooks) { if (active_hooks & sHooksToRemoveDuringSendInput & HOOK_KEYBD) // Keyboard hook was actually removed during SendInput. { // The above call to SendInput() has not only sent its own events, it has also emptied // the buffer of any events generated outside but during the SendInput. Since such // events are almost always physical events rather than simulated ones, it seems to do // more good than harm on average to consider any such changes to be physical. // The g_PhysicalKeyState array is also updated by GetModifierLRState(true), but only // for the modifier keys, not for all keys on the keyboard. Even if adjust all keys // is possible, it seems overly complex and it might impact performance more than it's // worth given the rarity of the user changing physical key states during a SendInput // and then wanting to explicitly retrieve that state via GetKeyState(Key, "P"). modLR_type mods_current = GetModifierLRState(true); // This also serves to correct the hook's logical modifiers, since hook was absent during the SendInput. modLR_type mods_changed_physically_during_send = aModsDuringSend ^ mods_current; g_modifiersLR_physical &= ~(mods_changed_physically_during_send & aModsDuringSend); // Remove those that changed from down to up. g_modifiersLR_physical |= mods_changed_physically_during_send & mods_current; // Add those that changed from up to down. g_HShwnd = GetForegroundWindow(); // An item done by ResetHook() that seems worthwhile here. // Most other things done by ResetHook() seem like they would do more harm than good to reset here // because of the the time the hook is typically missing is very short, usually under 30ms. } AddRemoveHooks(active_hooks, true); // Restore the hooks that were active before the SendInput. } #endif return; } // Since above didn't return, sSendMode == SM_PLAY. // It seems best not to call IsWindowHung() here because: // 1) It might improve script reliability to allow playback to a hung window because even though // the entire system would appear frozen, if the window becomes unhung, the keystrokes would // eventually get sent to it as intended (and the script may be designed to rely on this). // Furthermore, the user can press Ctrl-Alt-Del or Ctrl-Esc to unfreeze the system. // 2) It might hurt performance. // // During journal playback, it appears that LL hook receives events in realtime; its just that // keystrokes the hook passes through (or generates itself) don't actually hit the active window // until after the playback is done. Preliminary testing shows that the hook's disguise of Alt/Win // still function properly for Win/Alt hotkeys that use the playback method. sCurrentEvent = 0; // Reset for use by the hook below. Should be done BEFORE the hook is installed in the next line. #ifdef JOURNAL_RECORD_MODE // To record and analyze events via the above: // - Uncomment the line that defines this in the header file. // - Put breakpoint after the hook removes itself (a few lines below). Don't try to put breakpoint in RECORD hook // itself because it tends to freeze keyboard input (must press Ctrl-Alt-Del or Ctrl-Esc to unfreeze). // - Have the script send a keystroke (best to use non-character keystroke such as SendPlay {Shift}). // - It is now recording, so press the desired keys. // - Press Ctrl+Break, Ctrl-Esc, or Ctrl-Alt-Del to stop recording (which should then hit breakpoint below). // - Study contents of the sEventPB array, which contains the keystrokes just recorded. sEventCount = 0; // Used by RecordProc(). if ( !(g_PlaybackHook = SetWindowsHookEx(WH_JOURNALRECORD, RecordProc, GetModuleHandle(NULL), NULL)) ) return; #else if ( !(g_PlaybackHook = SetWindowsHookEx(WH_JOURNALPLAYBACK, PlaybackProc, GetModuleHandle(NULL), NULL)) ) return; // During playback, have the keybd hook (if it's installed) block presses of the Windows key. // This is done because the Windows key is about the only key (other than Ctrl-Esc or Ctrl-Alt-Del) // that takes effect immediately rather than getting buffered/postponed until after the playback. // It should be okay to set this after the playback hook is installed because playback shouldn't // actually begin until we have our thread do its first MsgSleep later below. g_BlockWinKeys = true; #endif // Otherwise, hook is installed, so: // Wait for the hook to remove itself because the script should not be allowed to continue // until the Send finishes. // GetMessage(single_msg_filter) can't be used because then our thread couldn't playback // keystrokes to one of its own windows. In addition, testing shows that it wouldn't // measurably improve performance anyway. // Note: User can't activate tray icon with mouse (because mouse is blocked), so there's // no need to call our main event loop merely to have the tray menu responsive. // Sleeping for 0 performs at least 15% worse than INTERVAL_UNSPECIFIED. I think this is // because the journal playback hook can operate only when this thread is in a message-pumping // state, and message pumping is far more efficient with GetMessage than PeekMessage. // Also note that both registered and hook hotkeys are noticed/caught during journal playback // (confirmed through testing). However, they are kept buffered until the Send finishes // because ACT_SEND and such are designed to be uninterruptible by other script threads; // also, it would be undesirable in almost any conceivable case. // // Use a loop rather than a single call to MsgSleep(WAIT_FOR_MESSAGES) because // WAIT_FOR_MESSAGES is designed only for use by WinMain(). The loop doesn't measurably // affect performance because there used to be the following here in place of the loop, // and it didn't perform any better: // GetMessage(&msg, NULL, WM_CANCELJOURNAL, WM_CANCELJOURNAL); while (g_PlaybackHook) SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED); // For maintainability, macro is used rather than optimizing/splitting the code it contains. g_BlockWinKeys = false; // Either the hook unhooked itself or the OS did due to Ctrl-Esc or Ctrl-Alt-Del. // MSDN: When an application sees a [system-generated] WM_CANCELJOURNAL message, it can assume // two things: the user has intentionally cancelled the journal record or playback mode, // and the system has already unhooked any journal record or playback hook procedures. if (!sEventPB[sEventCount - 1].message) // Playback hook can't do the final delay, so we do it here. // Don't do delay right here because the delay would be put into the array instead. aFinalKeyDelay = sEventPB[sEventCount - 1].time_to_wait; // GetModifierLRState(true) is not done because keystrokes generated by the playback hook // aren't really keystrokes in the sense that they affect global key state or modifier state. // They affect only the keystate retrieved when the target thread calls GetKeyState() // (GetAsyncKeyState can never see such changes, even if called from the target thread). // Furthermore, the hook (if present) continues to operate during journal playback, so it // will keep its own modifiers up-to-date if any physical or simulate keystrokes happen to // come in during playback (such keystrokes arrive in the hook in real time, but they don't // actually hit the active window until the playback finishes). } void CleanupEventArray(int aFinalKeyDelay) { if (sMaxEvents > (sSendMode == SM_INPUT ? MAX_INITIAL_EVENTS_SI : MAX_INITIAL_EVENTS_PB)) free(sEventSI); // Previous block was malloc'd vs. _alloc'd, so free it. Note that sEventSI and sEventPB are different views of the same variable. // The following must be done only after functions called above are done using it. But it must also be done // prior to our caller toggling capslock back on , to avoid the capslock keystroke from going into the array. sSendMode = SM_EVENT; DoKeyDelay(aFinalKeyDelay); // Do this only after resetting sSendMode above. Should be okay for mouse events too. } ///////////////////////////////// void DoKeyDelay(int aDelay) // Doesn't need to be thread safe because it should only ever be called from main thread. { if (aDelay < 0) // To support user-specified KeyDelay of -1 (fastest send rate). return; if (sSendMode) { if (sSendMode == SM_PLAY && aDelay > 0) // Zero itself isn't supported by playback hook, so no point in inserting such delays into the array. PutKeybdEventIntoArray(0, 0, 0, 0, aDelay); // Passing zero for vk and sc signals it that aExtraInfo contains the delay. //else for other types of arrays, never insert a delay or do one now. return; } if (g_os.IsWin9x()) { // Do a true sleep on Win9x because the MsgSleep() method is very inaccurate on Win9x // for some reason (a MsgSleep(1) causes a sleep between 10 and 55ms, for example): Sleep(aDelay); return; } SLEEP_WITHOUT_INTERRUPTION(aDelay); } void DoMouseDelay() // Helper function for the mouse functions below. { int mouse_delay = sSendMode == SM_PLAY ? g->MouseDelayPlay : g->MouseDelay; if (mouse_delay < 0) // To support user-specified KeyDelay of -1 (fastest send rate). return; if (sSendMode) { if (sSendMode == SM_PLAY && mouse_delay > 0) // Zero itself isn't supported by playback hook, so no point in inserting such delays into the array. PutKeybdEventIntoArray(0, 0, 0, 0, mouse_delay); // Passing zero for vk and sc signals it that aExtraInfo contains the delay. //else for other types of arrays, never insert a delay or do one now (caller should have already // checked that, so it's written this way here only for maintainability). return; } // I believe the varying sleep methods below were put in place to avoid issues when simulating // clicks on the script's own windows. There are extensive comments in MouseClick() and the // hook about these issues. Also, Sleep() is more accurate on Win9x than MsgSleep, which is // why it's used in that case. Here are more details from an older comment: // Always sleep a certain minimum amount of time between events to improve reliability, // but allow the user to specify a higher time if desired. Note that for Win9x, // a true Sleep() is done because it is much more accurate than the MsgSleep() method, // at least on Win98SE when short sleeps are done. UPDATE: A true sleep is now done // unconditionally if the delay period is small. This fixes a small issue where if // LButton is a hotkey that includes "MouseClick left" somewhere in its subroutine, // the script's own main window's title bar buttons for min/max/close would not // properly respond to left-clicks. By contrast, the following is no longer an issue // due to the dedicated thread in v1.0.39 (or more likely, due to an older change that // causes the tray menu to open upon RButton-up rather than down): // RButton is a hotkey that includes "MouseClick right" somewhere in its subroutine, // the user would not be able to correctly open the script's own tray menu via // right-click (note that this issue affected only the one script itself, not others). if (mouse_delay < 11 || (mouse_delay < 25 && g_os.IsWin9x())) Sleep(mouse_delay); else SLEEP_WITHOUT_INTERRUPTION(mouse_delay) } #ifndef MINIDLL void UpdateKeyEventHistory(bool aKeyUp, vk_type aVK, sc_type aSC) { if (!g_KeyHistory) // Don't access the array if it doesn't exist (i.e. key history is disabled). return; g_KeyHistory[g_KeyHistoryNext].key_up = aKeyUp; g_KeyHistory[g_KeyHistoryNext].vk = aVK; g_KeyHistory[g_KeyHistoryNext].sc = aSC; g_KeyHistory[g_KeyHistoryNext].event_type = 'i'; // Callers all want this. g_HistoryTickNow = GetTickCount(); g_KeyHistory[g_KeyHistoryNext].elapsed_time = (g_HistoryTickNow - g_HistoryTickPrev) / (float)1000; g_HistoryTickPrev = g_HistoryTickNow; HWND fore_win = GetForegroundWindow(); if (fore_win) { if (fore_win != g_HistoryHwndPrev) GetWindowText(fore_win, g_KeyHistory[g_KeyHistoryNext].target_window, _countof(g_KeyHistory[g_KeyHistoryNext].target_window)); else // i.e. avoid the call to GetWindowText() if possible. *g_KeyHistory[g_KeyHistoryNext].target_window = '\0'; } else _tcscpy(g_KeyHistory[g_KeyHistoryNext].target_window, _T("N/A")); g_HistoryHwndPrev = fore_win; // Update unconditionally in case it's NULL. if (++g_KeyHistoryNext >= g_MaxHistoryKeys) g_KeyHistoryNext = 0; } #endif ToggleValueType ToggleKeyState(vk_type aVK, ToggleValueType aToggleValue) // Toggle the given aVK into another state. For performance, it is the caller's responsibility to // ensure that aVK is a toggleable key such as capslock, numlock, insert, or scrolllock. // Returns the state the key was in before it was changed (but it's only a best-guess under Win9x). { // Can't use IsKeyDownAsync/GetAsyncKeyState() because it doesn't have this info: ToggleValueType starting_state = IsKeyToggledOn(aVK) ? TOGGLED_ON : TOGGLED_OFF; if (aToggleValue != TOGGLED_ON && aToggleValue != TOGGLED_OFF) // Shouldn't be called this way. return starting_state; if (starting_state == aToggleValue) // It's already in the desired state, so just return the state. return starting_state; if (aVK == VK_NUMLOCK) { #ifdef CONFIG_WIN9X if (g_os.IsWin9x()) { // For Win9x, we want to set the state unconditionally to be sure it's right. This is because // the retrieval of the Capslock state, for example, is unreliable, at least under Win98se // (probably due to lack of an AttachThreadInput() having been done). Although the // SetKeyboardState() method used by ToggleNumlockWin9x is not required for caps & scroll lock keys, // it is required for Numlock: ToggleNumlockWin9x(); return starting_state; // Best guess, but might be wrong. } #endif // Otherwise, NT/2k/XP: // Sending an extra up-event first seems to prevent the problem where the Numlock // key's indicator light doesn't change to reflect its true state (and maybe its // true state doesn't change either). This problem tends to happen when the key // is pressed while the hook is forcing it to be either ON or OFF (or it suppresses // it because it's a hotkey). Needs more testing on diff. keyboards & OSes: KeyEvent(KEYUP, aVK); } // Since it's not already in the desired state, toggle it: KeyEvent(KEYDOWNANDUP, aVK); // Fix for v1.0.40: IsKeyToggledOn()'s call to GetKeyState() relies on our thread having // processed messages. Confirmed necessary 100% of the time if our thread owns the active window. // v1.0.43: Extended the above fix to include all toggleable keys (not just Capslock) and to apply // to both directions (ON and OFF) since it seems likely to be needed for them all. bool our_thread_is_foreground; if (our_thread_is_foreground = (GetWindowThreadProcessId(GetForegroundWindow(), NULL) == g_MainThreadID)) // GetWindowThreadProcessId() tolerates a NULL hwnd. SLEEP_WITHOUT_INTERRUPTION(-1); if (aVK == VK_CAPITAL && aToggleValue == TOGGLED_OFF && IsKeyToggledOn(aVK)) { // Fix for v1.0.36.06: Since it's Capslock and it didn't turn off as attempted, it's probably because // the OS is configured to turn Capslock off only in response to pressing the SHIFT key (via Ctrl Panel's // Regional settings). So send shift to do it instead: KeyEvent(KEYDOWNANDUP, VK_SHIFT); if (our_thread_is_foreground) // v1.0.43: Added to try to achieve 100% reliability in all situations. SLEEP_WITHOUT_INTERRUPTION(-1); // Check msg queue to put SHIFT's turning off of Capslock into effect from our thread's POV. } return starting_state; } #ifdef CONFIG_WIN9X void ToggleNumlockWin9x() // Numlock requires a special method to toggle the state and its indicator light under Win9x. // Capslock and Scrolllock do not need this method, since keybd_event() works for them. { BYTE state[256]; GetKeyboardState((PBYTE)&state); state[VK_NUMLOCK] ^= 0x01; // Toggle the low-order bit to the opposite state. SetKeyboardState((PBYTE)&state); } //void CapslockOffWin9x() //{ // BYTE state[256]; // GetKeyboardState((PBYTE)&state); // state[VK_CAPITAL] &= ~0x01; // SetKeyboardState((PBYTE)&state); //} #endif /* void SetKeyState (vk_type vk, int aKeyUp) // Later need to adapt this to support Win9x by using SetKeyboardState for those OSs. { if (!vk) return; int key_already_up = !(GetKeyState(vk) & 0x8000); if ((key_already_up && aKeyUp) || (!key_already_up && !aKeyUp)) return; KeyEvent(aKeyUp, vk); } */ void SetModifierLRState(modLR_type aModifiersLRnew, modLR_type aModifiersLRnow, HWND aTargetWindow , bool aDisguiseDownWinAlt, bool aDisguiseUpWinAlt, DWORD aExtraInfo) // This function is designed to be called from only the main thread; it's probably not thread-safe. // Puts modifiers into the specified state, releasing or pressing down keys as needed. // The modifiers are released and pressed down in a very delicate order due to their interactions with // each other and their ability to show the Start Menu, activate the menu bar, or trigger the OS's language // bar hotkeys. Side-effects like these would occur if a more simple approach were used, such as releasing // all modifiers that are going up prior to pushing down the ones that are going down. // When the target layout has an altgr key, it is tempting to try to simplify things by removing MOD_LCONTROL // from aModifiersLRnew whenever aModifiersLRnew contains MOD_RALT. However, this a careful review how that // would impact various places below where sTargetLayoutHasAltGr is checked indicates that it wouldn't help. // Note that by design and as documented for ControlSend, aTargetWindow is not used as the target for the // various calls to KeyEvent() here. It is only used as a workaround for the GUI window issue described // at the bottom. { if (aModifiersLRnow == aModifiersLRnew) // They're already in the right state, so avoid doing all the checks. return; // Especially avoids the aTargetWindow check at the bottom. // Notes about modifier key behavior on Windows XP (these probably apply to NT/2k also, and has also // been tested to be true on Win98): The WIN and ALT keys are the problem keys, because if either is // released without having modified something (even another modifier), the WIN key will cause the // Start Menu to appear, and the ALT key will activate the menu bar of the active window (if it has one). // For example, a hook hotkey such as "$#c::Send text" (text must start with a lowercase letter // to reproduce the issue, because otherwise WIN would be auto-disguised as a side effect of the SHIFT // keystroke) would cause the Start Menu to appear if the disguise method below weren't used. // // Here are more comments formerly in SetModifierLRStateSpecific(), which has since been eliminated // because this function is sufficient: // To prevent it from activating the menu bar, the release of the ALT key should be disguised // unless a CTRL key is currently down. This is because CTRL always seems to avoid the // activation of the menu bar (unlike SHIFT, which sometimes allows the menu to be activated, // though this is hard to reproduce on XP). Another reason not to use SHIFT is that the OS // uses LAlt+Shift as a hotkey to switch languages. Such a hotkey would be triggered if SHIFT // were pressed down to disguise the release of LALT. // // Alt-down events are also disguised whenever they won't be accompanied by a Ctrl-down. // This is necessary whenever our caller does not plan to disguise the key itself. For example, // if "!a::Send Test" is a registered hotkey, two things must be done to avoid complications: // 1) Prior to sending the word test, ALT must be released in a way that does not activate the // menu bar. This is done by sandwiching it between a CTRL-down and a CTRL-up. // 2) After the send is complete, SendKeys() will restore the ALT key to the down position if // the user is still physically holding ALT down (this is done to make the logical state of // the key match its physical state, which allows the same hotkey to be fired twice in a row // without the user having to release and press down the ALT key physically). // The #2 case above is the one handled below by ctrl_wont_be_down. It is especially necessary // when the user releases the ALT key prior to releasing the hotkey suffix, which would otherwise // cause the menu bar (if any) of the active window to be activated. // // Some of the same comments above for ALT key apply to the WIN key. More about this issue: // Although the disguise of the down-event is usually not needed, it is needed in the rare case // where the user releases the WIN or ALT key prior to releasing the hotkey's suffix. // Although the hook could be told to disguise the physical release of ALT or WIN in these // cases, it's best not to rely on the hook since it is not always installed. // // Registered WIN and ALT hotkeys that don't use the Send command work okay except ALT hotkeys, // which if the user releases ALT prior the hotkey's suffix key, cause the menu bar to be activated. // Since it is unusual for users to do this and because it is standard behavior for ALT hotkeys // registered in the OS, fixing it via the hook seems like a low priority, and perhaps isn't worth // the added code complexity/size. But if there is ever a need to do so, the following note applies: // If the hook is installed, could tell it to disguise any need-to-be-disguised Alt-up that occurs // after receipt of the registered ALT hotkey. But what if that hotkey uses the send command: // there might be interference? Doesn't seem so, because the hook only disguises non-ignored events. // Set up some conditions so that the keystrokes that disguise the release of Win or Alt // are only sent when necessary (which helps avoid complications caused by keystroke interaction, // while improving performance): modLR_type aModifiersLRunion = aModifiersLRnow | aModifiersLRnew; // The set of keys that were or will be down. bool ctrl_not_down = !(aModifiersLRnow & (MOD_LCONTROL | MOD_RCONTROL)); // Neither CTRL key is down now. bool ctrl_will_not_be_down = !(aModifiersLRnew & (MOD_LCONTROL | MOD_RCONTROL)) // Nor will it be. && !(sTargetLayoutHasAltGr == CONDITION_TRUE && (aModifiersLRnew & MOD_RALT)); // Nor will it be pushed down indirectly due to AltGr. bool ctrl_nor_shift_nor_alt_down = ctrl_not_down // Neither CTRL key is down now. && !(aModifiersLRnow & (MOD_LSHIFT | MOD_RSHIFT | MOD_LALT | MOD_RALT)); // Nor is any SHIFT/ALT key. bool ctrl_or_shift_or_alt_will_be_down = !ctrl_will_not_be_down // CTRL will be down. || (aModifiersLRnew & (MOD_LSHIFT | MOD_RSHIFT | MOD_LALT | MOD_RALT)); // or SHIFT or ALT will be. // If the required disguise keys aren't down now but will be, defer the release of Win and/or Alt // until after the disguise keys are in place (since in that case, the caller wanted them down // as part of the normal operation here): bool defer_win_release = ctrl_nor_shift_nor_alt_down && ctrl_or_shift_or_alt_will_be_down; bool defer_alt_release = ctrl_not_down && !ctrl_will_not_be_down; // i.e. Ctrl not down but it will be. bool release_shift_before_alt_ctrl = defer_alt_release // i.e. Control is moving into the down position or... || !(aModifiersLRnow & (MOD_LALT | MOD_RALT)) && (aModifiersLRnew & (MOD_LALT | MOD_RALT)); // ...Alt is moving into the down position. // Concerning "release_shift_before_alt_ctrl" above: Its purpose is to prevent unwanted firing of the OS's // language bar hotkey. See the bottom of this function for more explanation. // ALT: bool disguise_alt_down = aDisguiseDownWinAlt && ctrl_not_down && ctrl_will_not_be_down; // Since this applies to both Left and Right Alt, don't take sTargetLayoutHasAltGr into account here. That is done later below. // WIN: The WIN key is successfully disguised under a greater number of conditions than ALT. // Since SendPlay can't display Start Menu, there's no need to send the disguise-keystrokes (such // keystrokes might cause unwanted effects in certain games): bool disguise_win_down = aDisguiseDownWinAlt && sSendMode != SM_PLAY && ctrl_not_down && ctrl_will_not_be_down && !(aModifiersLRunion & (MOD_LSHIFT | MOD_RSHIFT)) // And neither SHIFT key is down, nor will it be. && !(aModifiersLRunion & (MOD_LALT | MOD_RALT)); // And neither ALT key is down, nor will it be. bool release_lwin = (aModifiersLRnow & MOD_LWIN) && !(aModifiersLRnew & MOD_LWIN); bool release_rwin = (aModifiersLRnow & MOD_RWIN) && !(aModifiersLRnew & MOD_RWIN); bool release_lalt = (aModifiersLRnow & MOD_LALT) && !(aModifiersLRnew & MOD_LALT); bool release_ralt = (aModifiersLRnow & MOD_RALT) && !(aModifiersLRnew & MOD_RALT); bool release_lshift = (aModifiersLRnow & MOD_LSHIFT) && !(aModifiersLRnew & MOD_LSHIFT); bool release_rshift = (aModifiersLRnow & MOD_RSHIFT) && !(aModifiersLRnew & MOD_RSHIFT); // Handle ALT and WIN prior to the other modifiers because the "disguise" methods below are // only needed upon release of ALT or WIN. This is because such releases tend to have a better // chance of being "disguised" if SHIFT or CTRL is down at the time of the release. Thus, the // release of SHIFT or CTRL (if called for) is deferred until afterward. // ** WIN // Must be done before ALT in case it is relying on ALT being down to disguise the release WIN. // If ALT is going to be pushed down further below, defer_win_release should be true, which will make sure // the WIN key isn't released until after the ALT key is pushed down here at the top. // Also, WIN is a little more troublesome than ALT, so it is done first in case the ALT key // is down but will be going up, since the ALT key being down might help the WIN key. // For example, if you hold down CTRL, then hold down LWIN long enough for it to auto-repeat, // then release CTRL before releasing LWIN, the Start Menu would appear, at least on XP. // But it does not appear if CTRL is released after LWIN. // Also note that the ALT key can disguise the WIN key, but not vice versa. if (release_lwin) { if (!defer_win_release) { // Fixed for v1.0.25: To avoid triggering the system's LAlt+Shift language hotkey, the // Control key is now used to suppress LWIN/RWIN (preventing the Start Menu from appearing) // rather than the Shift key. This is definitely needed for ALT, but is done here for // WIN also in case ALT is down, which might cause the use of SHIFT as the disguise key // to trigger the language switch. if (ctrl_nor_shift_nor_alt_down && aDisguiseUpWinAlt // Nor will they be pushed down later below, otherwise defer_win_release would have been true and we couldn't get to this point. && sSendMode != SM_PLAY) // SendPlay can't display Start Menu, so disguise not needed (also, disguise might mess up some games). KeyEvent(KEYDOWNANDUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Disguise key release to suppress Start Menu. // The above event is safe because if we're here, it means VK_CONTROL will not be // pressed down further below. In other words, we're not defeating the job // of this function by sending these disguise keystrokes. KeyEvent(KEYUP, VK_LWIN, 0, NULL, false, aExtraInfo); } // else release it only after the normal operation of the function pushes down the disguise keys. } else if (!(aModifiersLRnow & MOD_LWIN) && (aModifiersLRnew & MOD_LWIN)) // Press down LWin. { if (disguise_win_down) KeyEvent(KEYDOWN, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. KeyEvent(KEYDOWN, VK_LWIN, 0, NULL, false, aExtraInfo); if (disguise_win_down) KeyEvent(KEYUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. } if (release_rwin) { if (!defer_win_release) { if (ctrl_nor_shift_nor_alt_down && MOD_RWIN && sSendMode != SM_PLAY) KeyEvent(KEYDOWNANDUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Disguise key release to suppress Start Menu. KeyEvent(KEYUP, VK_RWIN, 0, NULL, false, aExtraInfo); } // else release it only after the normal operation of the function pushes down the disguise keys. } else if (!(aModifiersLRnow & MOD_RWIN) && (aModifiersLRnew & MOD_RWIN)) // Press down RWin. { if (disguise_win_down) KeyEvent(KEYDOWN, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. KeyEvent(KEYDOWN, VK_RWIN, 0, NULL, false, aExtraInfo); if (disguise_win_down) KeyEvent(KEYUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that the Start Menu does not appear. } // ** SHIFT (PART 1 OF 2) if (release_shift_before_alt_ctrl) { if (release_lshift) KeyEvent(KEYUP, VK_LSHIFT, 0, NULL, false, aExtraInfo); if (release_rshift) KeyEvent(KEYUP, VK_RSHIFT, 0, NULL, false, aExtraInfo); } // ** ALT if (release_lalt) { if (!defer_alt_release) { if (ctrl_not_down && aDisguiseUpWinAlt) KeyEvent(KEYDOWNANDUP, VK_CONTROL, 0, NULL, false, aExtraInfo); // Disguise key release to suppress menu activation. KeyEvent(KEYUP, VK_LMENU, 0, NULL, false, aExtraInfo); } } else if (!(aModifiersLRnow & MOD_LALT) && (aModifiersLRnew & MOD_LALT)) { if (disguise_alt_down) KeyEvent(KEYDOWN, VK_CONTROL, 0, NULL, false, aExtraInfo); // Ensures that menu bar is not activated. KeyEvent(KEYDOWN, VK_LMENU, 0, NULL, false, aExtraInfo); if (disguise_alt_down) KeyEvent(KEYUP, VK_CONTROL, 0, NULL, false, aExtraInfo);
tinku99/ahkdll
ff231e157d94708fc132a5d65c3b474c69e141e1
Fixed Send sleep e.g. Send abc{100}def
diff --git a/source/MemoryModule.c b/source/MemoryModule.c index f746b71..dfa6e15 100644 --- a/source/MemoryModule.c +++ b/source/MemoryModule.c @@ -1,488 +1,488 @@ /* * Memory DLL loading code * Version 0.0.2 * * Copyright (c) 2004-2011 by Joachim Bauch / [email protected] * http://www.joachim-bauch.de * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is MemoryModule.c * * The Initial Developer of the Original Code is Joachim Bauch. * * Portions created by Joachim Bauch are Copyright (C) 2004-2011 * Joachim Bauch. All Rights Reserved. * */ #ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) #endif #ifdef _WIN64 #define POINTER_TYPE ULONGLONG #else #define POINTER_TYPE DWORD #endif #include <Windows.h> #include <winnt.h> #ifdef DEBUG_OUTPUT #include <stdio.h> #endif #ifndef IMAGE_SIZEOF_BASE_RELOCATION // Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!? #define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION)) #endif #include "MemoryModule.h" typedef struct { PIMAGE_NT_HEADERS headers; unsigned char *codeBase; HMODULE *modules; int numModules; int initialized; } MEMORYMODULE, *PMEMORYMODULE; typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] #ifdef DEBUG_OUTPUT static void OutputLastError(const char *msg) { LPVOID tmp; char *tmpmsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL); tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3); sprintf(tmpmsg, "%s: %s", msg, tmp); OutputDebugString(tmpmsg); LocalFree(tmpmsg); LocalFree(tmp); } #endif static void CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) { int i, size; unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_READWRITE); section->Misc.PhysicalAddress = (POINTER_TYPE)dest; memset(dest, 0, size); } // section is empty continue; } // commit memory block and copy data from dll dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE); memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); section->Misc.PhysicalAddress = (POINTER_TYPE)dest; } } // Protection flags for memory pages (Executable, Readable, Writeable) static int ProtectionFlags[2][2][2] = { { // not executable {PAGE_NOACCESS, PAGE_WRITECOPY}, {PAGE_READONLY, PAGE_READWRITE}, }, { // executable {PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY}, {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE}, }, }; static void FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); #ifdef _WIN64 POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); #else #define imageOffset 0 #endif // loop through all sections and change access flags for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page") #endif ; } } #ifndef _WIN64 #undef imageOffset #endif } static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; #endif int type, offset; // the upper 4 bits define the type of relocation type = *relInfo >> 12; // the lower 12 bits define the offset offset = *relInfo & 0xfff; switch (type) { case IMAGE_REL_BASED_ABSOLUTE: // skip relocation break; case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address patchAddrHL = (DWORD *) (dest + offset); *patchAddrHL += delta; break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif default: //printf("Unknown relocation: %d\n", type); break; } } // advance to next relocation block relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } static int BuildImportTable(PMEMORYMODULE module) { int result=1; unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle = LoadLibraryA((LPCSTR) (codeBase + importDesc->Name)); if (handle == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif result = 0; break; } module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); } if (*funcRef == 0) { result = 0; break; } } if (!result) { break; } } } return result; } HMEMORYMODULE MemoryLoadLibrary(const void *data) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("Not a valid executable file.\n"); #endif return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("No PE header found.\n"); #endif return NULL; } // reserve memory for image of library code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); if (code == NULL) { #if DEBUG_OUTPUT OutputLastError("Can't reserve memory"); #endif return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; result->modules = NULL; result->initialized = 0; // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... VirtualAlloc(code, old_header->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_READWRITE); // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_READWRITE); // copy PE header to code memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections(data, old_header, result); // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugString("Library has no entry point.\n"); #endif goto error; } // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); if (!successfull) { #if DEBUG_OUTPUT OutputDebugString("Can't attach library.\n"); #endif goto error; } result->initialized = 1; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { - if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { + if (stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) { int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module != NULL) { if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } if (module->modules != NULL) { // free previously opened libraries for (i=0; i<module->numModules; i++) { if (module->modules[i] != INVALID_HANDLE_VALUE) { FreeLibrary(module->modules[i]); } } free(module->modules); } if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); } HeapFree(GetProcessHeap(), 0, module); } } diff --git a/source/keyboard_mouse.cpp b/source/keyboard_mouse.cpp index d12ea3b..52aa509 100644 --- a/source/keyboard_mouse.cpp +++ b/source/keyboard_mouse.cpp @@ -1,636 +1,636 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 "keyboard_mouse.h" #include "globaldata.h" // for g->KeyDelay #include "application.h" // for MsgSleep() #include "util.h" // for strlicmp() #include "window.h" // for IsWindowHung() // Added for v1.0.25. Search on sPrevEventType for more comments: static KeyEventTypes sPrevEventType; static vk_type sPrevVK = 0; // For v1.0.25, the below is static to track it in between sends, so that the below will continue // to work: // Send {LWinDown} // Send {LWinUp} ; Should still open the Start Menu even though it's a separate Send. static vk_type sPrevEventModifierDown = 0; static modLR_type sModifiersLR_persistent = 0; // Tracks this script's own lifetime/persistent modifiers (the ones it caused to be persistent and thus is responsible for tracking). // v1.0.44.03: Below supports multiple keyboard layouts better by having script adapt to active window's layout. #define MAX_CACHED_LAYOUTS 10 // Hard to imagine anyone using more languages/layouts than this, but even if they do it will still work; performance would just be a little worse due to being uncached. static CachedLayoutType sCachedLayout[MAX_CACHED_LAYOUTS] = {{0}}; static HKL sTargetKeybdLayout; // Set by SendKeys() for use by the functions it calls directly and indirectly. static ResultType sTargetLayoutHasAltGr; // // v1.0.43: Support for SendInput() and journal-playback hook: #define MAX_INITIAL_EVENTS_SI 500UL // sizeof(INPUT) == 28 as of 2006. Since Send is called so often, and since most Sends are short, reducing the load on the stack is also a deciding factor for these. #define MAX_INITIAL_EVENTS_PB 1500UL // sizeof(PlaybackEvent) == 8, so more events are justified before resorting to malloc(). static LPINPUT sEventSI; // No init necessary. An array that's allocated/deallocated by SendKeys(). static PlaybackEvent *&sEventPB = (PlaybackEvent *&)sEventSI; static UINT sEventCount, sMaxEvents; // Number of items in the above arrays and the current array capacity. static UINT sCurrentEvent; static modLR_type sEventModifiersLR; // Tracks the modifier state to following the progress/building of the SendInput array. static POINT sSendInputCursorPos; // Tracks/predicts cursor position as SendInput array is built. #ifndef MINIDLL static HookType sHooksToRemoveDuringSendInput; #endif static SendModes sSendMode = SM_EVENT; // Whether a SendInput or Hook array is currently being constructed. static bool sAbortArraySend; // No init needed. static bool sFirstCallForThisEvent; // static bool sInBlindMode; // static DWORD sThisEventTime; // // Dynamically resolve SendInput() because otherwise the app won't launch at all on Windows 95/NT-pre-SP3: typedef UINT (WINAPI *MySendInputType)(UINT, LPINPUT, int); static MySendInputType sMySendInput = (MySendInputType)GetProcAddress(GetModuleHandle(_T("user32")), "SendInput"); // Above will be NULL for Win95/NT-pre-SP3. void DisguiseWinAltIfNeeded(vk_type aVK) // For v1.0.25, the following situation is fixed by the code below: If LWin or LAlt // becomes a persistent modifier (e.g. via Send {LWin down}) and the user physically // releases LWin immediately before: 1) the {LWin up} is scheduled; and 2) SendKey() // returns. Then SendKey() will push the modifier back down so that it is in effect // for other things done by its caller (SendKeys) and also so that if the Send // operation ends, the key will still be down as the user intended (to modify future // keystrokes, physical or simulated). However, since that down-event is followed // immediately by an up-event, the Start Menu appears for WIN-key or the active // window's menu bar is activated for ALT-key. SOLUTION: Disguise Win-up and Alt-up // events in these cases. This workaround has been successfully tested. It's also // limited is scope so that a script can still explicitly invoke the Start Menu with // "Send {LWin}", or activate the menu bar with "Send {Alt}". // The check of sPrevEventModifierDown allows "Send {LWinDown}{LWinUp}" etc., to // continue to work. // v1.0.40: For maximum flexibility and minimum interference while in blind mode, // don't disguise Win and Alt keystrokes then. { // Caller has ensured that aVK is about to have a key-up event, so if the event immediately // prior to this one is a key-down of the same type of modifier key, it's our job here // to send the disguising keystrokes now (if appropriate). if (sPrevEventType == KEYDOWN && sPrevEventModifierDown != aVK && !sInBlindMode // SendPlay mode can't display Start Menu, so no need for disguise keystrokes (such keystrokes might cause // unwanted effects in certain games): && ((aVK == VK_LWIN || aVK == VK_RWIN) && (sPrevVK == VK_LWIN || sPrevVK == VK_RWIN) && sSendMode != SM_PLAY || (aVK == VK_LMENU || (aVK == VK_RMENU && sTargetLayoutHasAltGr != CONDITION_TRUE)) && (sPrevVK == VK_LMENU || sPrevVK == VK_RMENU))) KeyEvent(KEYDOWNANDUP, g_MenuMaskKey); // Disguise it to suppress Start Menu or prevent activation of active window's menu bar. } // moved from SendKeys void SendUnicodeChar(wchar_t aChar, int aModifiers = -1) { - // Set modifier keystate for consistent results. If not specified by caller, default to releasing - // Alt/Ctrl/Shift since these are known to interfere in some cases, and because SendAsc() does it - // (except for LAlt). Leave LWin/RWin as they are, for consistency with SendAsc(). - if (aModifiers == -1) - { - aModifiers = sSendMode ? sEventModifiersLR : GetModifierLRState(); - aModifiers &= ~(MOD_LALT | MOD_RALT | MOD_LCONTROL | MOD_RCONTROL | MOD_LSHIFT | MOD_RSHIFT); - } - SetModifierLRState((modLR_type)aModifiers, sSendMode ? sEventModifiersLR : GetModifierLRState(), NULL, false, true, KEY_IGNORE); - if (sSendMode == SM_INPUT) { // Calling SendInput() now would cause characters to appear out of sequence. // Instead, put them into the array and allow them to be sent in sequence. PutKeybdEventIntoArray(0, 0, aChar, KEYEVENTF_UNICODE, KEY_IGNORE); PutKeybdEventIntoArray(0, 0, aChar, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, KEY_IGNORE); return; } //else caller has ensured sSendMode is SM_EVENT. In that mode, events are sent one at a time, // so it is safe to immediately call SendInput(). SM_PLAY is not supported; for simplicity, // SendASC() is called instead of this function. Although this means Unicode chars probably // won't work, it seems better than sending chars out of order. One possible alternative could // be to "flush" the event array, but since SendInput and SendEvent are probably much more common, // this is left for a future version. + // Set modifier keystate for consistent results. If not specified by caller, default to releasing + // Alt/Ctrl/Shift since these are known to interfere in some cases, and because SendAsc() does it + // (except for LAlt). Leave LWin/RWin as they are, for consistency with SendAsc(). + if (aModifiers == -1) + { + aModifiers = sSendMode ? sEventModifiersLR : GetModifierLRState(); + aModifiers &= ~(MOD_LALT | MOD_RALT | MOD_LCONTROL | MOD_RCONTROL | MOD_LSHIFT | MOD_RSHIFT); + } + SetModifierLRState((modLR_type)aModifiers, sSendMode ? sEventModifiersLR : GetModifierLRState(), NULL, false, true, KEY_IGNORE); + INPUT u_input[2]; u_input[0].type = INPUT_KEYBOARD; u_input[0].ki.wVk = 0; u_input[0].ki.wScan = aChar; u_input[0].ki.dwFlags = KEYEVENTF_UNICODE; u_input[0].ki.time = 0; // L25: Set dwExtraInfo to ensure AutoHotkey ignores the event; otherwise it may trigger a SCxxx hotkey (where xxx is u_code). u_input[0].ki.dwExtraInfo = KEY_IGNORE; u_input[1].type = INPUT_KEYBOARD; u_input[1].ki.wVk = 0; u_input[1].ki.wScan = aChar; u_input[1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP; u_input[1].ki.time = 0; u_input[1].ki.dwExtraInfo = KEY_IGNORE; SendInput(2, u_input, sizeof(INPUT)); } void SendKeys(LPTSTR aKeys, bool aSendRaw, SendModes aSendModeOrig, HWND aTargetWindow, unsigned int sendahk) // The aKeys string must be modifiable (not constant), since for performance reasons, // it's allowed to be temporarily altered by this function. mThisHotkeyModifiersLR, if non-zero, // should be the set of modifiers used to trigger the hotkey that called the subroutine // containing the Send that got us here. If any of those modifiers are still down, // they will be released prior to sending the batch of keys specified in <aKeys>. // v1.0.43: aSendModeOrig was added. { if (!*aKeys) return; global_struct &g = *::g; // Reduces code size and may improve performance. // For performance and also to reserve future flexibility, recognize {Blind} only when it's the first item // in the string. if (sInBlindMode = !aSendRaw && !_tcsnicmp(aKeys, _T("{Blind}"), 7)) // Don't allow {Blind} while in raw mode due to slight chance {Blind} is intended to be sent as a literal string. // Blind Mode (since this seems too obscure to document, it's mentioned here): Blind Mode relies // on modifiers already down for something like ^c because ^c is saying "manifest a ^c", which will // happen if ctrl is already down. By contrast, Blind does not release shift to produce lowercase // letters because avoiding that adds flexibility that couldn't be achieved otherwise. // Thus, ^c::Send {Blind}c produces the same result when ^c is substituted for the final c. // But Send {Blind}{LControl down} will generate the extra events even if ctrl already down. aKeys += 7; // Remove "{Blind}" from further consideration. int orig_key_delay = g.KeyDelay; int orig_press_duration = g.PressDuration; if (aSendModeOrig == SM_INPUT || aSendModeOrig == SM_INPUT_FALLBACK_TO_PLAY) // Caller has ensured aTargetWindow==NULL for SendInput and SendPlay modes. { // Both of these modes fall back to a different mode depending on whether some other script // is running with a keyboard/mouse hook active. Of course, the detection of this isn't foolproof // because older versions of AHK may be running and/or other apps with LL keyboard hooks. It's // just designed to add a lot of value for typical usage because SendInput is preferred due to it // being considerably faster than SendPlay, especially for long replacements when the CPU is under // heavy load. if ( !sMySendInput // Win95/NT-pre-SP3 don't support SendInput, so fall back to the specified mode. || SystemHasAnotherKeybdHook() // This function has been benchmarked to ensure it doesn't yield our timeslice, etc. 200 calls take 0ms according to tick-count, even when CPU is maxed. || !aSendRaw && SystemHasAnotherMouseHook() && tcscasestr(aKeys, _T("{Click")) ) // Ordered for short-circuit boolean performance. v1.0.43.09: Fixed to be strcasestr vs. !strcasestr { // Need to detect in advance what type of array to build (for performance and code size). That's why // it done this way, and here are the comments about it: // strcasestr() above has an unwanted amount of overhead if aKeys is huge, but it seems acceptable // because it's called only when system has another mouse hook but *not* another keybd hook (very rare). // Also, for performance reasons, {LButton and such are not checked for, which is documented and seems // justified because the new {Click} method is expected to become prevalent, especially since this // whole section only applies when the new SendInput mode is in effect. // Finally, checking aSendRaw isn't foolproof because the string might contain {Raw} prior to {Click, // but the complexity and performance of checking for that seems unjustified given the rarity, // especially since there are almost never any consequences to reverting to hook mode vs. SendInput. if (aSendModeOrig == SM_INPUT_FALLBACK_TO_PLAY) aSendModeOrig = SM_PLAY; else // aSendModeOrig == SM_INPUT, so fall back to EVENT. { aSendModeOrig = SM_EVENT; // v1.0.43.08: When SendInput reverts to SendEvent mode, the majority of users would want // a fast sending rate that is more comparable to SendInput's speed that the default KeyDelay // of 10ms. PressDuration may be generally superior to KeyDelay because it does a delay after // each changing of modifier state (which tends to improve reliability for certain apps). // The following rules seem likely to be the best benefit in terms of speed and reliability: // KeyDelay 0+,-1+ --> -1, 0 // KeyDelay -1, 0+ --> -1, 0 // KeyDelay -1,-1 --> -1, -1 g.PressDuration = (g.KeyDelay < 0 && g.PressDuration < 0) ? -1 : 0; g.KeyDelay = -1; // Above line must be done before this one. } } else // SendInput is available and no other impacting hooks are obviously present on the system, so use SendInput unconditionally. aSendModeOrig = SM_INPUT; // Resolve early so that other sections don't have to consider SM_INPUT_FALLBACK_TO_PLAY a valid value. } // Might be better to do this prior to changing capslock state. UPDATE: In v1.0.44.03, the following section // has been moved to the top of the function because: // 1) For ControlSend, GetModifierLRState() might be more accurate if the threads are attached beforehand. // 2) Determines sTargetKeybdLayout and sTargetLayoutHasAltGr early (for maintainability). bool threads_are_attached = false; // Set default. DWORD keybd_layout_thread = 0; // DWORD target_thread; // Doesn't need init. if (aTargetWindow) // Caller has ensured this is NULL for SendInput and SendPlay modes. { if ((target_thread = GetWindowThreadProcessId(aTargetWindow, NULL)) // Assign. && target_thread != g_MainThreadID && !IsWindowHung(aTargetWindow)) { threads_are_attached = AttachThreadInput(g_MainThreadID, target_thread, TRUE) != 0; keybd_layout_thread = target_thread; // Testing shows that ControlSend benefits from the adapt-to-layout technique too. } //else no target thread, or it's our thread, or it's hung; so keep keybd_layout_thread at its default. } else { // v1.0.48.01: On Vista or later, work around the fact that an "L" keystroke (physical or artificial) will // lock the computer whenever either Windows key is physically pressed down (artificially releasing the // Windows key isn't enough to solve it because Win+L is apparently detected aggressively like // Ctrl-Alt-Delete. Unlike the handling of SM_INPUT in another section, this one here goes into // effect for all Sends because waiting for an "L" keystroke to be sent would be too late since the // Windows would have already been artificially released by then, so IsKeyDownAsync() wouldn't be // able to detect when the user physically releases the key. if ( (g_script.mThisHotkeyModifiersLR & (MOD_LWIN|MOD_RWIN)) // Limit the scope to only those hotkeys that have a Win modifier, since anything outside that scope hasn't been fully analyzed. #ifndef MINIDLL && (GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)50 // Ensure g_script.mThisHotkeyModifiersLR is up-to-date enough to be reliable. #endif && aSendModeOrig == SM_EVENT // SM_INPUT's workaround for Vista is handled by another section. v1.0.48.04: Fixed sSendMode to be aSendModeOrig. && !sInBlindMode // The philosophy of blind-mode is that the script should have full control, so don't do any waiting during blind mode. && g_os.IsWinVistaOrLater() // Only Vista (and presumably later OSes) check the physical state of the Windows key for Win+L. && GetCurrentThreadId() == g_MainThreadID // Exclude the hook thread because it isn't allowed to call anything like MsgSleep, nor are any calls from the hook thread within the understood/analyzed scope of this workaround. ) { bool wait_for_win_key_release; if (aSendRaw) wait_for_win_key_release = StrChrAny(aKeys, _T("Ll")) != NULL; else { // It seems worthwhile to scan for any "L" characters to avoid waiting for the release // of the Windows key when there are no L's. For performance and code size, the check // below isn't comprehensive (e.g. it fails to consider things like {L} and #L). // Although RegExMatch() could be used instead of the below, that would use up one of // the RegEx cache entries, plus it would probably perform worse. So scan manually. LPTSTR L_pos, brace_pos; for (wait_for_win_key_release = false, brace_pos = aKeys; L_pos = StrChrAny(brace_pos, _T("Ll"));) { // Encountering a #L seems too rare, and the consequences too mild (or nonexistent), to // justify the following commented-out section: //if (L_pos > aKeys && L_pos[-1] == '#') // A simple check; it won't detect things like #+L. // brace_pos = L_pos + 1; //else if (!(brace_pos = StrChrAny(L_pos + 1, _T("{}"))) || *brace_pos == '{') // See comment below. { wait_for_win_key_release = true; break; } //else it found a '}' without a preceding '{', which means this "L" is inside braces. // For simplicity, ignore such L's (probably not a perfect check, but seems worthwhile anyway). } } if (wait_for_win_key_release) while (IsKeyDownAsync(VK_LWIN) || IsKeyDownAsync(VK_RWIN)) // Even if the keyboard hook is installed, it seems best to use IsKeyDownAsync() vs. g_PhysicalKeyState[] because it's more likely to produce consistent behavior. SLEEP_WITHOUT_INTERRUPTION(INTERVAL_UNSPECIFIED); // Seems best not to allow other threads to launch, for maintainability and because SendKeys() isn't designed to be interruptible. } // v1.0.44.03: The following change is meaningful only to people who use more than one keyboard layout. // It seems that the vast majority of them would want the Send command (as well as other features like // Hotstrings and the Input command) to adapt to the keyboard layout of the active window (or target window // in the case of ControlSend) rather than sticking with the script's own keyboard layout. In addition, // testing shows that this adapt-to-layout method costs almost nothing in performance, especially since // the active window, its thread, and its layout are retrieved only once for each Send rather than once // for each keystroke. HWND active_window; if (active_window = GetForegroundWindow()) keybd_layout_thread = GetWindowThreadProcessId(active_window, NULL); //else no foreground window, so keep keybd_layout_thread at default. } #ifdef AHKX sTargetKeybdLayout = g_HKL; // If keybd_layout_thread==0, this will get our thread's own layout, which seems like the best/safest default. sTargetLayoutHasAltGr = LayoutHasAltGr(sTargetKeybdLayout); // Note that WM_INPUTLANGCHANGEREQUEST is not monitored by MsgSleep for the purpose of caching our thread's keyboard layout. This is because it would be unreliable if another msg pump such as MsgBox is running. Plus it hardly helps perf. at all, and hurts maintainability. #else sTargetKeybdLayout = GetKeyboardLayout(keybd_layout_thread); // If keybd_layout_thread==0, this will get our thread's own layout, which seems like the best/safest default. sTargetLayoutHasAltGr = LayoutHasAltGr(sTargetKeybdLayout); // Note that WM_INPUTLANGCHANGEREQUEST is not monitored by MsgSleep for the purpose of caching our thread's keyboard layout. This is because it would be unreliable if another msg pump such as MsgBox is running. Plus it hardly helps perf. at all, and hurts maintainability. #endif // Below is now called with "true" so that the hook's modifier state will be corrected (if necessary) // prior to every send. modLR_type mods_current = GetModifierLRState(true); // Current "logical" modifier state. // Make a best guess of what the physical state of the keys is prior to starting (there's no way // to be certain without the keyboard hook). Note: We only want those physical // keys that are also logically down (it's possible for a key to be down physically // but not logically such as when R-control, for example, is a suffix hotkey and the // user is physically holding it down): modLR_type mods_down_physically_orig, mods_down_physically_and_logically , mods_down_physically_but_not_logically_orig; if (g_KeybdHook) { // Since hook is installed, use its more reliable tracking to determine which // modifiers are down. mods_down_physically_orig = g_modifiersLR_physical; mods_down_physically_and_logically = g_modifiersLR_physical & g_modifiersLR_logical; // intersect mods_down_physically_but_not_logically_orig = g_modifiersLR_physical & ~g_modifiersLR_logical; } else // Use best-guess instead. { // Even if TickCount has wrapped due to system being up more than about 49 days, // DWORD subtraction still gives the right answer as long as g_script.mThisHotkeyStartTime // itself isn't more than about 49 days ago: if ((GetTickCount() - g_script.mThisHotkeyStartTime) < (DWORD)g_HotkeyModifierTimeout) // Elapsed time < timeout-value mods_down_physically_orig = mods_current & g_script.mThisHotkeyModifiersLR; // Bitwise AND is set intersection. else // Since too much time as passed since the user pressed the hotkey, it seems best, // based on the action that will occur below, to assume that no hotkey modifiers // are physically down: mods_down_physically_orig = 0; mods_down_physically_and_logically = mods_down_physically_orig; mods_down_physically_but_not_logically_orig = 0; // There's no way of knowing, so assume none. } // Any of the external modifiers that are down but NOT due to the hotkey are probably // logically down rather than physically (perhaps from a prior command such as // "Send, {CtrlDown}". Since there's no way to be sure without the keyboard hook or some // driver-level monitoring, it seems best to assume that // they are logically vs. physically down. This value contains the modifiers that // we will not attempt to change (e.g. "Send, A" will not release the LWin // before sending "A" if this value indicates that LWin is down). The below sets // the value to be all the down-keys in mods_current except any that are physically // down due to the hotkey itself. UPDATE: To improve the above, we now exclude from // the set of persistent modifiers any that weren't made persistent by this script. // Such a policy seems likely to do more good than harm as there have been cases where // a modifier was detected as persistent just because #HotkeyModifier had timed out // while the user was still holding down the key, but then when the user released it, // this logic here would think it's still persistent and push it back down again // to enforce it as "always-down" during the send operation. Thus, the key would // basically get stuck down even after the send was over: sModifiersLR_persistent &= mods_current & ~mods_down_physically_and_logically; modLR_type persistent_modifiers_for_this_SendKeys, extra_persistent_modifiers_for_blind_mode; if (sInBlindMode) { // The following value is usually zero unless the user is currently holding down // some modifiers as part of a hotkey. These extra modifiers are the ones that // this send operation (along with all its calls to SendKey and similar) should // consider to be down for the duration of the Send (unless they go up via an // explicit {LWin up}, etc.) extra_persistent_modifiers_for_blind_mode = mods_current & ~sModifiersLR_persistent; persistent_modifiers_for_this_SendKeys = mods_current; } else { extra_persistent_modifiers_for_blind_mode = 0; persistent_modifiers_for_this_SendKeys = sModifiersLR_persistent; } // Above: // Keep sModifiersLR_persistent and persistent_modifiers_for_this_SendKeys in sync with each other from now on. // By contrast to persistent_modifiers_for_this_SendKeys, sModifiersLR_persistent is the lifetime modifiers for // this script that stay in effect between sends. For example, "Send {LAlt down}" leaves the alt key down // even after the Send ends, by design. // // It seems best not to change persistent_modifiers_for_this_SendKeys in response to the user making physical // modifier changes during the course of the Send. This is because it seems more often desirable that a constant // state of modifiers be kept in effect for the entire Send rather than having the user's release of a hotkey // modifier key, which typically occurs at some unpredictable time during the Send, to suddenly alter the nature // of the Send in mid-stride. Another reason is to make the behavior of Send consistent with that of SendInput. // The default behavior is to turn the capslock key off prior to sending any keys // because otherwise lowercase letters would come through as uppercase and vice versa. ToggleValueType prior_capslock_state; if (threads_are_attached || !g_os.IsWin9x()) { // Only under either of the above conditions can the state of Capslock be reliably // retrieved and changed. Remember that apps like MS Word have an auto-correct feature that // might make it wrongly seem that the turning off of Capslock below needs a Sleep(0) to take effect. prior_capslock_state = g.StoreCapslockMode && !sInBlindMode ? ToggleKeyState(VK_CAPITAL, TOGGLED_OFF) : TOGGLE_INVALID; // In blind mode, don't do store capslock (helps remapping and also adds flexibility). } else // OS is Win9x and threads are not attached. { // Attempt to turn off capslock, but never attempt to turn it back on because we can't // reliably detect whether it was on beforehand. Update: This didn't do any good, so // it's disabled for now: //CapslockOffWin9x(); prior_capslock_state = TOGGLE_INVALID; } // sSendMode must be set only after setting Capslock state above, because the hook method // is incapable of changing the on/off state of toggleable keys like Capslock. // However, it can change Capslock state as seen in the window to which playback events are being // sent; but the behavior seems inconsistent and might vary depending on OS type, so it seems best // not to rely on it. sSendMode = aSendModeOrig; if (sSendMode) // Build an array. We're also responsible for setting sSendMode to SM_EVENT prior to returning. { size_t mem_size; if (sSendMode == SM_INPUT) { mem_size = MAX_INITIAL_EVENTS_SI * sizeof(INPUT); sMaxEvents = MAX_INITIAL_EVENTS_SI; } else // Playback type. { mem_size = MAX_INITIAL_EVENTS_PB * sizeof(PlaybackEvent); sMaxEvents = MAX_INITIAL_EVENTS_PB; } // _alloca() is used to avoid the overhead of malloc/free (99% of Sends will thus fit in stack memory). // _alloca() never returns a failure code, it just raises an exception (e.g. stack overflow). InitEventArray(_alloca(mem_size), sMaxEvents, mods_current); } bool blockinput_prev = g_BlockInput; bool do_selective_blockinput = (g_BlockInputMode == TOGGLE_SEND || g_BlockInputMode == TOGGLE_SENDANDMOUSE) && !sSendMode && !aTargetWindow && g_os.IsWinNT4orLater(); if (do_selective_blockinput) Line::ScriptBlockInput(true); // Turn it on unconditionally even if it was on, since Ctrl-Alt-Del might have disabled it. vk_type vk; sc_type sc; modLR_type key_as_modifiersLR = 0; modLR_type mods_for_next_key = 0; // Above: For v1.0.35, it was changed to modLR vs. mod so that AltGr keys such as backslash and '{' // are supported on layouts such as German when sending to apps such as Putty that are fussy about // which ALT key is held down to produce the character. vk_type this_event_modifier_down; size_t key_text_length, key_name_length; TCHAR *end_pos, *space_pos, *next_word, old_char, single_char_string[2]; KeyEventTypes event_type; int repeat_count, click_x, click_y; bool move_offset, key_down_is_persistent; DWORD placeholder; single_char_string[1] = '\0'; // Terminate in advance. LONG_OPERATION_INIT // Needed even for SendInput/Play. for (; *aKeys; ++aKeys, sPrevEventModifierDown = this_event_modifier_down) { this_event_modifier_down = 0; // Set default for this iteration, overridden selectively below. if (!sSendMode) LONG_OPERATION_UPDATE_FOR_SENDKEYS // This does not measurably affect the performance of SendPlay/Event. if (!aSendRaw && _tcschr(_T("^+!#{}"), *aKeys)) { switch (*aKeys) { case '^': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LCONTROL|MOD_RCONTROL))) mods_for_next_key |= MOD_LCONTROL; // else don't add it, because the value of mods_for_next_key may also used to determine // which keys to release after the key to which this modifier applies is sent. // We don't want persistent modifiers to ever be released because that's how // AutoIt2 behaves and it seems like a reasonable standard. continue; case '+': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LSHIFT|MOD_RSHIFT))) mods_for_next_key |= MOD_LSHIFT; continue; case '!': if (!(persistent_modifiers_for_this_SendKeys & (MOD_LALT|MOD_RALT))) mods_for_next_key |= MOD_LALT; continue; case '#': if (g_script.mIsAutoIt2) // Since AutoIt2 ignores these, ignore them if script is in AutoIt2 mode. continue; if (!(persistent_modifiers_for_this_SendKeys & (MOD_LWIN|MOD_RWIN))) mods_for_next_key |= MOD_LWIN; continue; case '}': continue; // Important that these be ignored. Be very careful about changing this, see below. case '{': { if ( !(end_pos = _tcschr(aKeys + 1, '}')) ) // Ignore it and due to rarity, don't reset mods_for_next_key. continue; // This check is relied upon by some things below that assume a '}' is present prior to the terminator. aKeys = omit_leading_whitespace(aKeys + 1); // v1.0.43: Skip leading whitespace inside the braces to be more flexible. if ( !(key_text_length = end_pos - aKeys) ) { if (end_pos[1] == '}') { // The literal string "{}}" has been encountered, which is interpreted as a single "}". ++end_pos; key_text_length = 1; } else if (IS_SPACE_OR_TAB(end_pos[1])) // v1.0.48: Support "{} down}", "{} downtemp}" and "{} up}". { next_word = omit_leading_whitespace(end_pos + 1); if ( !_tcsnicmp(next_word, _T("Down"), 4) // "Down" or "DownTemp" (or likely enough). || !_tcsnicmp(next_word, _T("Up"), 2) ) { if ( !(end_pos = _tcschr(next_word, '}')) ) // See comments at similar section above. continue; key_text_length = end_pos - aKeys; // This result must be non-zero due to the checks above. } else goto brace_case_end; // The loop's ++aKeys will now skip over the '}', ignoring it. } else // Empty braces {} were encountered (or all whitespace, but literal whitespace isn't sent). goto brace_case_end; // The loop's ++aKeys will now skip over the '}', ignoring it. } if (!_tcsnicmp(aKeys, _T("Click"), 5)) { *end_pos = '\0'; // Temporarily terminate the string here to omit the closing brace from consideration below. ParseClickOptions(omit_leading_whitespace(aKeys + 5), click_x, click_y, vk , event_type, repeat_count, move_offset); *end_pos = '}'; // Undo temp termination. if (repeat_count < 1) // Allow {Click 100, 100, 0} to do a mouse-move vs. click (but modifiers like ^{Click..} aren't supported in this case. MouseMove(click_x, click_y, placeholder, g.DefaultMouseSpeed, move_offset); else // Use SendKey because it supports modifiers (e.g. ^{Click}) SendKey requires repeat_count>=1. SendKey(vk, 0, mods_for_next_key, persistent_modifiers_for_this_SendKeys , repeat_count, event_type, 0, aTargetWindow, click_x, click_y, move_offset); goto brace_case_end; // This {} item completely handled, so move on to next. } else if (!_tcsnicmp(aKeys, _T("Raw"), 3)) // This is used by auto-replace hotstrings too. { // As documented, there's no way to switch back to non-raw mode afterward since there's no // correct way to support special (non-literal) strings such as {Raw Off} while in raw mode. aSendRaw = true; goto brace_case_end; // This {} item completely handled, so move on to next. } // Since above didn't "goto", this item isn't {Click}. event_type = KEYDOWNANDUP; // Set defaults. repeat_count = 1; // key_name_length = key_text_length; // *end_pos = '\0'; // Temporarily terminate the string here to omit the closing brace from consideration below. if (space_pos = StrChrAny(aKeys, _T(" \t"))) // Assign. Also, it relies on the fact that {} key names contain no spaces. { old_char = *space_pos; *space_pos = '\0'; // Temporarily terminate here so that TextToVK() can properly resolve a single char. key_name_length = space_pos - aKeys; // Override the default value set above. next_word = omit_leading_whitespace(space_pos + 1); UINT next_word_length = (UINT)(end_pos - next_word); if (next_word_length > 0) { if (!_tcsnicmp(next_word, _T("Down"), 4)) { event_type = KEYDOWN; // v1.0.44.05: Added key_down_is_persistent (which is not initialized except here because // it's only applicable when event_type==KEYDOWN). It avoids the following problem: // When a key is remapped to become a modifier (such as F1::Control), launching one of // the script's own hotkeys via F1 would lead to bad side-effects if that hotkey uses // the Send command. This is because the Send command assumes that any modifiers pressed // down by the script itself (such as Control) are intended to stay down during all // keystrokes generated by that script. To work around this, something like KeyWait F1 // would otherwise be needed. within any hotkey triggered by the F1 key. key_down_is_persistent = _tcsnicmp(next_word + 4, _T("Temp"), 4); // "DownTemp" means non-persistent. } else if (!_tcsicmp(next_word, _T("Up"))) event_type = KEYUP; else repeat_count = ATOI(next_word); // Above: If negative or zero, that is handled further below. // There is no complaint for values <1 to support scripts that want to conditionally send // zero keystrokes, e.g. Send {a %Count%} } } vk = TextToVK(aKeys, &mods_for_next_key, true, false, sTargetKeybdLayout); // false must be passed due to below. sc = vk ? 0 : TextToSC(aKeys); // If sc is 0, it will be resolved by KeyEvent() later. if (!vk && !sc && ctoupper(aKeys[0]) == 'V' && ctoupper(aKeys[1]) == 'K') { LPTSTR sc_string = StrChrAny(aKeys + 2, _T("Ss")); // Look for the "SC" that demarks the scan code. if (sc_string && ctoupper(sc_string[1]) == 'C') sc = (sc_type)_tcstol(sc_string + 2, NULL, 16); // Convert from hex. // else leave sc set to zero and just get the specified VK. This supports Send {VKnn}. vk = (vk_type)_tcstol(aKeys + 2, NULL, 16); // Convert from hex. } if (space_pos) // undo the temporary termination *space_pos = old_char; *end_pos = '}'; // undo the temporary termination if (repeat_count < 1) goto brace_case_end; // Gets rid of one level of indentation. Well worth it. if (vk || sc) { if (key_as_modifiersLR = KeyToModifiersLR(vk, sc)) // Assign { if (!aTargetWindow) { if (event_type == KEYDOWN) // i.e. make {Shift down} have the same effect {ShiftDown} { this_event_modifier_down = vk; if (key_down_is_persistent) // v1.0.44.05. sModifiersLR_persistent |= key_as_modifiersLR; persistent_modifiers_for_this_SendKeys |= key_as_modifiersLR; // v1.0.44.06: Added this line to fix the fact that "DownTemp" should keep the key pressed down after the send. } else if (event_type == KEYUP) // *not* KEYDOWNANDUP, since that would be an intentional activation of the Start Menu or menu bar. { DisguiseWinAltIfNeeded(vk); sModifiersLR_persistent &= ~key_as_modifiersLR; // By contrast with KEYDOWN, KEYUP should also remove this modifier // from extra_persistent_modifiers_for_blind_mode if it happens to be // in there. For example, if "#i::Send {LWin Up}" is a hotkey, // LWin should become persistently up in every respect. extra_persistent_modifiers_for_blind_mode &= ~key_as_modifiersLR; // Fix for v1.0.43: Also remove LControl if this key happens to be AltGr. if (vk == VK_RMENU && sTargetLayoutHasAltGr == CONDITION_TRUE) // It is AltGr. extra_persistent_modifiers_for_blind_mode &= ~MOD_LCONTROL; // Since key_as_modifiersLR isn't 0, update to reflect any changes made above: persistent_modifiers_for_this_SendKeys = sModifiersLR_persistent | extra_persistent_modifiers_for_blind_mode; } // else must never change sModifiersLR_persistent in response to KEYDOWNANDUP // because that would break existing scripts. This is because that same // modifier key may have been pushed down via {ShiftDown} rather than "{Shift Down}". // In other words, {Shift} should never undo the effects of a prior {ShiftDown} // or {Shift down}. } //else don't add this event to sModifiersLR_persistent because it will not be // manifest via keybd_event. Instead, it will done via less intrusively // (less interference with foreground window) via SetKeyboardState() and // PostMessage(). This change is for ControlSend in v1.0.21 and has been // documented. } // Below: sModifiersLR_persistent stays in effect (pressed down) even if the key // being sent includes that same modifier. Surprisingly, this is how AutoIt2 // behaves also, which is good. Example: Send, {AltDown}!f ; this will cause // Alt to still be down after the command is over, even though F is modified // by Alt. SendKey(vk, sc, mods_for_next_key, persistent_modifiers_for_this_SendKeys , repeat_count, event_type, key_as_modifiersLR, aTargetWindow);
tinku99/ahkdll
9de0d757d54447723f8d45f711ae6738211d65f4
Fixed another bug with script parameters
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index ffcddec..b7b1231 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,662 +1,663 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "windows.h" // N11 #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; // Naveen v1. hThread2 and threadCount // Todo: remove these as multithreading was implemented // with multiple loading of the dll under separate names. static int threadCount = 1 ; static HANDLE hThread2; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); // need better cleanup: windows, variables, no exit from script break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE - LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.argv)+1)*sizeof(WCHAR)); - MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.argv,-1,wargv,(_tcslen(nameHinstanceP.argv)+1)*sizeof(WCHAR)); + LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); + MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else - LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.argv,&dllargc); + LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc); #endif int i; + if (*nameHinstanceP.args) // Only process if parameters were given for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,(bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = !nameHinstanceP.istext ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef _USRDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #else #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #endif #endif #ifndef MINIDLL /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(bool kill) { int lpExitCode = 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if (!kill) for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < 10; i++) { PostMessage(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0); Sleep(50); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else
tinku99/ahkdll
a42d17816bed113342d461b3274c1d1b354d98d6
Fixed script parameters for dll and removed A_ScriptParams
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index e56cebf..ffcddec 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,758 +1,755 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "windows.h" // N11 #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; // Naveen v1. hThread2 and threadCount // Todo: remove these as multithreading was implemented // with multiple loading of the dll under separate names. static int threadCount = 1 ; static HANDLE hThread2; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); // need better cleanup: windows, variables, no exit from script break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; int dllargc = 0; #ifndef _UNICODE LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.argv)+1)*sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.argv,-1,wargv,(_tcslen(nameHinstanceP.argv)+1)*sizeof(WCHAR)); LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc); #else LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.argv,&dllargc); #endif int i; for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name. { #ifndef _UNICODE param = (TCHAR *) _alloca((wcslen(dllargv[i])+1)*sizeof(CHAR)); WideCharToMultiByte(CP_ACP,0,wargv,-1,param,(wcslen(dllargv[i])+1)*sizeof(CHAR),0,0); #else param = dllargv[i]; // For performance and convenience. #endif if (switch_processing_is_complete) // All args are now considered to be input parameters for the script. { if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Insist that switches be an exact match for the allowed values to cut down on ambiguity. // For example, if the user runs "CompiledScript.exe /find", we want /find to be considered // an input parameter for the script rather than a switch: else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart"))) restart_mode = true; else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force"))) g_ForceLaunch = true; else if (!_tcsicmp(param, _T("/ErrorStdOut"))) g_script.mErrorStdOut = true; else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script. { ++i; // Consume the next parameter too, because it's associated with this one. if (i >= dllargc) // Missing the expected filename parameter. return CRITICAL_ERROR; // For performance and simplicity, open/create the file unconditionally and keep it open until exit. g_script.mIncludeLibraryFunctionsThenExit = new TextFile; if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file. return CRITICAL_ERROR; } else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn { // Default codepage for the script file, NOT the default for commands used by it. g_DefaultScriptCodepage = ATOU(param + 3); } #ifdef CONFIG_DEBUGGER // Allow a debug session to be initiated by command-line. else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '=')) { if (param[6] == '=') { param += 7; LPTSTR c = _tcsrchr(param, ':'); if (c) { StringTCharToChar(param, g_DebuggerHost, (int)(c-param)); StringTCharToChar(c + 1, g_DebuggerPort); } else { StringTCharToChar(param, g_DebuggerHost); g_DebuggerPort = "9000"; } } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. - break; // No more switches allowed after this point. + --i; // Make the loop process this item again so that it will be treated as a script param. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 - Var *A_ScriptParams; - A_ScriptParams = g_script.FindOrAddVar(_T("A_ScriptParams")); - A_ScriptParams->Assign(nameHinstanceP.args); Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,(bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = !nameHinstanceP.istext ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef _USRDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #else #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #endif #endif #ifndef MINIDLL /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(bool kill) { int lpExitCode = 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if (!kill) for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < 10; i++) { PostMessage(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0); Sleep(50); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT UINT_PTR ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_AutoHotkey, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/UINT_PTR* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/UINT_PTR* aLabelPointer) { if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; diff --git a/source/exports.cpp b/source/exports.cpp index 0456b0e..97a7bc1 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,753 +1,753 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL - if (Hotkey::sHotkeyCount>aHotkeyCount > aHotkeyCount) + if (Hotkey::sHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. AssignVariant(*aFunc->mParam[1].var, param2, false); if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 { AssignVariant(*aFunc->mParam[2].var, param3, false); if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 { AssignVariant(*aFunc->mParam[3].var, param4, false); if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 { AssignVariant(*aFunc->mParam[4].var, param5, false); if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 { AssignVariant(*aFunc->mParam[5].var, param6, false); if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 { AssignVariant(*aFunc->mParam[6].var, param7, false); if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 { AssignVariant(*aFunc->mParam[7].var, param8, false); if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 { AssignVariant(*aFunc->mParam[8].var, param9, false); if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 { AssignVariant(*aFunc->mParam[9].var, param10, false); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; }
tinku99/ahkdll
1258eb262a41b5dfe222019de6c8538af9bbd1fe
Changed Alias() to work if first parameter is alias too
diff --git a/source/exports.cpp b/source/exports.cpp index 4885165..0456b0e 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,753 +1,753 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} UINT_PTR com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} UINT_PTR com_ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} UINT_PTR com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC UINT_PTR com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} UINT_PTR com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL UINT_PTR com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} UINT_PTR com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT UINT_PTR ahkFindFunc(LPTSTR funcname) { return (UINT_PTR)g_script.FindFunc(funcname); } EXPORT UINT_PTR ahkFindLabel(LPTSTR aLabelName) { return (UINT_PTR)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT UINT_PTR ahkExecuteLine(UINT_PTR line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (UINT_PTR)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (UINT_PTR) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL - if (Hotkey::sHotkeyCount>aHotkeyCount) + if (Hotkey::sHotkeyCount>aHotkeyCount > aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } // Scan for undeclared local variables which are named the same as a global variable. // This loop has two purposes (but it's all handled in PreprocessLocalVars()): // // 1) Allow super-global variables to be referenced above the point of declaration. // This is a bit of a hack to work around the fact that variable references are // resolved as they are encountered, before all declarations have been processed. // // 2) Warn the user (if appropriate) since they probably meant it to be global. // for (int i = 0; i < g_script.mFuncCount; ++i) { Func &func = *g_script.mFunc[i]; if (!func.mIsBuiltIn) { g_script.PreprocessLocalVars(func, func.mVar, func.mVarCount); g_script.PreprocessLocalVars(func, func.mLazyVar, func.mLazyVarCount); } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT UINT_PTR addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (UINT_PTR) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. AssignVariant(*aFunc->mParam[1].var, param2, false); if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 { AssignVariant(*aFunc->mParam[2].var, param3, false); if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 { AssignVariant(*aFunc->mParam[3].var, param4, false); if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 { AssignVariant(*aFunc->mParam[4].var, param5, false); if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 { AssignVariant(*aFunc->mParam[5].var, param6, false); if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 { AssignVariant(*aFunc->mParam[6].var, param7, false); if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 { AssignVariant(*aFunc->mParam[7].var, param8, false); if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 { AssignVariant(*aFunc->mParam[8].var, param9, false); if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 { AssignVariant(*aFunc->mParam[9].var, param10, false); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp index aa7b312..0738aa1 100644 --- a/source/lowlevelbif.cpp +++ b/source/lowlevelbif.cpp @@ -1,126 +1,126 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" #define BIF(fun) void fun(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) BIF(BIF_FindFunc) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } BIF(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00 { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname); aResultToken.value_int64 = (__int64)ahkFindLabel(labelname); return; } BIF(BIF_Getvar) { int i = 0; if (aParam[0]->symbol == SYM_VAR) i = (int)aParam[0]->var; aResultToken.value_int64 = i; } BIF(BIF_Static) { if (aParam[0]->symbol == SYM_VAR) { Var *var = aParam[0]->var; if (var->mType == VAR_ALIAS) var = var->mAliasFor; var->mAttrib |= VAR_LOCAL_STATIC; } } BIF(BIF_Alias) { ExprTokenType &aParam0 = *aParam[0]; ExprTokenType &aParam1 = *aParam[1]; if (aParam0.symbol == SYM_VAR) { - Var &var = *aParam0.var; + Var &var = (aParam[0]->var->mType == VAR_ALIAS ? *aParam0.var->ResolveAlias() : *aParam0.var); UINT_PTR len = 0; switch (aParam1.symbol) { case SYM_VAR: case SYM_INTEGER: len = (UINT_PTR)(aParam[1]->var->mType == VAR_ALIAS ? aParam1.var->ResolveAlias() : aParam1.var); break; // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll case SYM_OPERAND: len = (UINT_PTR)ATOI64(aParam1.marker); } var.mType = len ? VAR_ALIAS : VAR_NORMAL; var.mByteLength = len; } } BIF(BIF_CacheEnable) { if (aParam[0]->symbol == SYM_VAR) { (aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var) ->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; } } BIF(BIF_getTokenValue) { ExprTokenType *token = aParam[0]; if (token->symbol != SYM_INTEGER) return; token = (ExprTokenType*) token->value_int64; if (token->symbol == SYM_VAR) { Var &var = *token->var; VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE); if (cache_attrib) { aResultToken.symbol = (SymbolType) (cache_attrib >> 4); aResultToken.value_int64 = var.mContentsInt64; } else if (var.mAttrib & VAR_ATTRIB_OBJECT) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = var.mObject; } else { aResultToken.symbol = SYM_OPERAND; aResultToken.marker = var.mCharContents; } } else { aResultToken.symbol = token->symbol; aResultToken.value_int64 = token->value_int64; } if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->AddRef(); } \ No newline at end of file
tinku99/ahkdll
2678888364baf42b07e397ba3f3008f1fec3d6f9
Changed ResolveGui to set name even if a gui is found
diff --git a/source/script_gui.cpp b/source/script_gui.cpp index 50185eb..c002243 100644 --- a/source/script_gui.cpp +++ b/source/script_gui.cpp @@ -1,611 +1,611 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifndef MINIDLL #include "script.h" #include "globaldata.h" // for a lot of things #include "application.h" // for MsgSleep() #include "window.h" // for SetForegroundWindowEx() #include "qmath.h" // for qmathLog() GuiType *Script::ResolveGui(LPTSTR aBuf, LPTSTR &aCommand, LPTSTR *aName, size_t *aNameLength) { LPTSTR name_marker = NULL; size_t name_length = 0; Line::ConvertGuiName(aBuf, aCommand, &name_marker, &name_length); if (!name_marker) // i.e. no name was specified. { if (g->GuiDefaultWindowValid()) return g->GuiDefaultWindow; else if (g->GuiDefaultWindow) // i.e. it contains a Gui name but no valid Gui. name_marker = g->GuiDefaultWindow->mName; else name_marker = _T("1"); // For backward-compatibility. // Return the default Gui name to our caller in case it wants to create a Gui. if (aName) *aName = name_marker; // Caller must copy the name before releasing g->GuiDefaultWindow. if (aNameLength) *aNameLength = _tcslen(name_marker); // GuiDefaultWindowValid() has already searched and determined the Gui does not exist. return NULL; } // Set defaults: indicate this name can't be used to create a new Gui. if (aName) *aName = NULL; if (aNameLength) *aNameLength = 0; if (!name_length || name_length > MAX_VAR_NAME_LENGTH) return NULL; // Invalid name. // Make a temporary null-terminated copy of the name for use below. TCHAR name[MAX_VAR_NAME_LENGTH + 1]; tmemcpy(name, name_marker, name_length); name[name_length] = '\0'; + // Even if Gui with this name exists, if aName != NULL, our caller wants to know what + // name to give a new or existing Gui. Before returning the name, ensure it is valid. At the very + // least, space must be outlawed for Gui label names and +OwnerGUINAME. Requiring the + // name to be valid as a variable name allows for possible future use of the Gui name + // as part of a variable or function name. + if (aName) + { + if (Var::ValidateName(name, true, false)) + { + // This name is okay. + *aName = name_marker; + if (aNameLength) + *aNameLength = name_length; + } + // Otherwise, leave it set to NULL so our caller knows it is invalid. + } + if (IsPureNumeric(name, TRUE, FALSE) == PURE_INTEGER) // Allow negatives, for flexibility. { __int64 gui_num = ATOI64(name); if (gui_num < 1 || gui_num > 99 // The range of valid Gui numbers prior to v1.1.03. || name_length > 2) // Length is also checked because that's how it used to be. { // *aName is left as NULL in this case to prevent a new Gui from being created // with this number as its name if below fails to find a Gui. Otherwise, it // might be possible for that Gui's name to conflict with a future Gui's HWND. return GuiType::FindGui((HWND)gui_num); } // Otherwise, it's a number between 1 and 99 which is composed of no more than two // characters; i.e. it must be treated as a name for backward compatibility reasons. // ConvertGuiName() already stripped the leading 0 out of something like "01", for // backward-compatibility. } // Search for the Gui! if (GuiType *found_gui = GuiType::FindGui(name)) return found_gui; - - // Since no Gui with this name exists, if aName != NULL, our caller wants to know what - // name to give a new Gui. Before returning the name, ensure it is valid. At the very - // least, space must be outlawed for Gui label names and +OwnerGUINAME. Requiring the - // name to be valid as a variable name allows for possible future use of the Gui name - // as part of a variable or function name. - if (aName) - { - if (Var::ValidateName(name, true, false)) - { - // This name is okay. - *aName = name_marker; - if (aNameLength) - *aNameLength = name_length; - } - // Otherwise, leave it set to NULL so our caller knows it is invalid. - } return NULL; } GuiType *GuiType::FindGui(LPTSTR aName) { for (int i = 0; i < g_guiCount; ++i) if (!_tcsicmp(g_gui[i]->mName, aName)) return g_gui[i]; return NULL; } GuiType *GuiType::FindGui(HWND aHwnd) { // The loop will usually find it on the first iteration since // the #1 window is default and thus most commonly used. for (int i = 0; i < g_guiCount; ++i) if (g_gui[i]->mHwnd == aHwnd) return g_gui[i]; return NULL; } GuiType *global_struct::GuiDefaultWindowValid() { if (!GuiDefaultWindow) { // Default Gui hasn't been set yet for this thread, so find Gui 1. if (GuiDefaultWindow = GuiType::FindGui(_T("1"))) // Assignment. GuiDefaultWindow->AddRef(); return GuiDefaultWindow; } // Update GuiDefaultWindow if it has been destroyed and recreated. return GuiType::ValidGui(GuiDefaultWindow); } GuiType *GuiType::ValidGui(GuiType *&aGuiRef) { if (aGuiRef && !aGuiRef->mHwnd) { // Gui has been destroyed. GuiType *recreated_gui; if ( !(recreated_gui = GuiType::FindGui(aGuiRef->mName)) ) return NULL; // Gui is not valid, so return NULL. // Gui has been recreated, so update the reference: recreated_gui->AddRef(); aGuiRef->Release(); aGuiRef = recreated_gui; } // Above verified it either points to a valid Gui or is NULL. return aGuiRef; } ResultType Script::PerformGui(LPTSTR aBuf, LPTSTR aParam2, LPTSTR aParam3, LPTSTR aParam4) { LPTSTR aCommand; // Set by ResolveGui(). LPTSTR name; // Set by ResolveGui() if it returns NULL. size_t name_length; // GuiType *pgui = ResolveGui(aBuf, aCommand, &name, &name_length); if (!pgui && !name) return ScriptError(ERR_INVALID_GUI_NAME ERR_ABORT, aBuf); GuiCommands gui_command = Line::ConvertGuiCommand(aCommand); if (gui_command == GUI_CMD_INVALID) // This is caught at load-time 99% of the time and can only occur here if the sub-command name // or Gui name is contained in a variable reference. return ScriptError(ERR_PARAM1_INVALID ERR_ABORT, aCommand); PRIVATIZE_S_DEREF_BUF; // See comments in GuiControl() about this. ResultType result = OK; // Set default return value for use with all instances of "goto" further below. // EVERYTHING below this point should use "result" and "goto return_the_result" instead of "return". // First completely handle any sub-command that doesn't require the window to exist. // In other words, don't auto-create the window before doing this command like we do // for the others: switch(gui_command) { case GUI_CMD_DESTROY: if (pgui) result = GuiType::Destroy(*pgui); goto return_the_result; case GUI_CMD_DEFAULT: if (!pgui) { // Create a dummy structure to hold the name. For simplicity and maintainability, // a full GuiType structure is constructed. We can't actually create the Gui yet, // since that would prevent +Owner%N% from working and possibly break other scripts // which rely on the old behaviour. if (pgui = new GuiType()) { if (pgui->mName = tmalloc(name_length + 1)) { tmemcpy(pgui->mName, name, name_length); pgui->mName[name_length] = '\0'; } else { delete pgui; pgui = NULL; } } } // Change the "default" member, not g->GuiWindow because that contains the original window // responsible for launching this thread, which should not be changed because it is used to // produce the contents of A_Gui. if (pgui) { if (g->GuiDefaultWindow) g->GuiDefaultWindow->Release(); pgui->AddRef(); g->GuiDefaultWindow = pgui; } else result = ScriptError(ERR_OUTOFMEM); goto return_the_result; } // If the window doesn't currently exist, don't auto-create it for those commands for // which it wouldn't make sense. Note that things like FONT and COLOR are allowed to // auto-create the window, since those commands can be legitimately used prior to the // first "Gui Add" command. Also, it seems best to allow SHOW even though all it will // do is create and display an empty window. if (!pgui) { switch(gui_command) { case GUI_CMD_SUBMIT: case GUI_CMD_CANCEL: case GUI_CMD_FLASH: case GUI_CMD_MINIMIZE: case GUI_CMD_MAXIMIZE: case GUI_CMD_RESTORE: goto return_the_result; // Nothing needs to be done since the window object doesn't exist. // v1.0.43.09: // Don't overload "+LastFound" because it would break existing scripts that rely on the window // being created by +LastFound. case GUI_CMD_OPTIONS: if (!_tcsicmp(aCommand, _T("+LastFoundExist"))) { g->hWndLastUsed = NULL; goto return_the_result; } break; } if (g_guiCount == g_guiCountMax) { // g_gui is full or hasn't been allocated yet, so allocate or expand it. Start at a low // number since most scripts don't use many Gui windows, and double each time for simplicity // and to avoid lots of intermediate reallocations if the script creates many Gui windows. int new_max = g_guiCountMax ? g_guiCountMax * 2 : 8; GuiType **new_gui_array = (GuiType **)realloc(g_gui, new_max * sizeof(GuiType *)); if (!new_gui_array) { result = FAIL; // No error displayed since extremely rare. goto return_the_result; } g_gui = new_gui_array; g_guiCountMax = new_max; } // Otherwise: Create the object and (later) its window, since all the other sub-commands below need it: for (;;) // For break, to reduce repetition of cleanup-on-failure code. { if (pgui = new GuiType()) { if (pgui->mControl = (GuiControlType *)malloc(GUI_CONTROL_BLOCK_SIZE * sizeof(GuiControlType))) { if (pgui->mName = tmalloc(name_length + 1)) { tmemcpy(pgui->mName, name, name_length); pgui->mName[name_length] = '\0'; pgui->mControlCapacity = GUI_CONTROL_BLOCK_SIZE; g_gui[g_guiCount++] = pgui; break; } free(pgui->mControl); } delete pgui; } result = FAIL; // No error displayed since extremely rare. goto return_the_result; } } GuiType &gui = *pgui; // For performance. // Now handle any commands that should be handled prior to creation of the window in the case // where the window doesn't already exist: bool set_last_found_window = false; ToggleValueType own_dialogs = TOGGLE_INVALID; if (gui_command == GUI_CMD_OPTIONS) if (!gui.ParseOptions(aCommand, set_last_found_window, own_dialogs)) { result = FAIL; // It already displayed the error. goto return_the_result; } // Create the window if needed. Since it should not be possible for our window to get destroyed // without our knowing about it (via the explicit handling in its window proc), it shouldn't // be necessary to check the result of IsWindow(gui.mHwnd): if (!gui.mHwnd && !gui.Create()) { GuiType::Destroy(gui); // Get rid of the object so that it stays in sync with the window's existence. result = ScriptError(_T("Could not create window.") ERR_ABORT); goto return_the_result; } // After creating the window, return from any commands that were fully handled above: if (gui_command == GUI_CMD_OPTIONS) { if (set_last_found_window) g->hWndLastUsed = gui.mHwnd; // Fix for v1.0.35.05: Must do the following only if gui_command==GUI_CMD_OPTIONS, otherwise // the own_dialogs setting will get reset during other commands such as "Gui Show", "Gui Add" if (own_dialogs != TOGGLE_INVALID) // v1.0.35.06: Plus or minus "OwnDialogs" was present rather than being entirely absent. { if (g->DialogOwner) g->DialogOwner->Release(); if (own_dialogs == TOGGLED_ON) { gui.AddRef(); g->DialogOwner = &gui; } else g->DialogOwner = NULL; // Reset to NULL when "-OwnDialogs" is present. } goto return_the_result; } GuiControls gui_control_type = GUI_CONTROL_INVALID; int index; switch (gui_command) { case GUI_CMD_ADD: if ( !(gui_control_type = Line::ConvertGuiControl(aParam2)) ) { result = ScriptError(ERR_PARAM2_INVALID ERR_ABORT, aParam2); goto return_the_result; } result = gui.AddControl(gui_control_type, aParam3, aParam4); // It already displayed any error. goto return_the_result; case GUI_CMD_MARGIN: if (*aParam2) gui.mMarginX = ATOI(aParam2); // Seems okay to allow negative margins. if (*aParam3) gui.mMarginY = ATOI(aParam3); // Seems okay to allow negative margins. goto return_the_result; case GUI_CMD_MENU: UserMenu *menu; if (*aParam2) { // By design, the below will give a slightly misleading error if the specified menu is the // TRAY menu, since it should be obvious that it cannot be used as a menu bar (since it // must always be of the popup type): if ( !(menu = FindMenu(aParam2)) || menu == g_script.mTrayMenu ) // Relies on short-circuit boolean. { result = ScriptError(ERR_MENU ERR_ABORT, aParam2); goto return_the_result; } menu->Create(MENU_TYPE_BAR); // Ensure the menu physically exists and is the "non-popup" type (for a menu bar). } else menu = NULL; SetMenu(gui.mHwnd, menu ? menu->mMenu : NULL); // Add or remove the menu. goto return_the_result; case GUI_CMD_SHOW: result = gui.Show(aParam2, aParam3); goto return_the_result; case GUI_CMD_SUBMIT: result = gui.Submit(_tcsicmp(aParam2, _T("NoHide"))); goto return_the_result; case GUI_CMD_CANCEL: result = gui.Cancel(); goto return_the_result; case GUI_CMD_MINIMIZE: // If the window is hidden, it is unhidden as a side-effect (this happens even for SW_SHOWMINNOACTIVE). ShowWindow(gui.mHwnd, SW_MINIMIZE); goto return_the_result; case GUI_CMD_MAXIMIZE: ShowWindow(gui.mHwnd, SW_MAXIMIZE); // If the window is hidden, it is unhidden as a side-effect. goto return_the_result; case GUI_CMD_RESTORE: ShowWindow(gui.mHwnd, SW_RESTORE); // If the window is hidden, it is unhidden as a side-effect. goto return_the_result; case GUI_CMD_FONT: result = gui.SetCurrentFont(aParam2, aParam3); goto return_the_result; case GUI_CMD_LISTVIEW: case GUI_CMD_TREEVIEW: if (*aParam2) { GuiIndexType control_index = gui.FindControl(aParam2); // Search on either the control's variable name or its ClassNN. if (control_index != -1) // Must compare directly to -1 due to unsigned. { GuiControlType &control = gui.mControl[control_index]; // For maintainability, and might slightly reduce code size. if (gui_command == GUI_CMD_LISTVIEW) { if (control.type == GUI_CONTROL_LISTVIEW) // v1.0.46.09: Must validate that it's the right type of control; otherwise some LV_* functions can crash due to the control not having malloc'd the special ListView struct that tracks column attributes. gui.mCurrentListView = &control; //else mismatched control type, so just leave it unchanged. } else // GUI_CMD_TREEVIEW { if (control.type == GUI_CONTROL_TREEVIEW) gui.mCurrentTreeView = &control; //else mismatched control type, so just leave it unchanged. } } //else it seems best never to change it to be "no control" since it doesn't seem to have much use. } goto return_the_result; case GUI_CMD_TAB: { TabIndexType prev_tab_index = gui.mCurrentTabIndex; TabControlIndexType prev_tab_control_index = gui.mCurrentTabControlIndex; if (!*aParam2 && !*aParam3) // Both the tab control number and the tab number were omitted. gui.mCurrentTabControlIndex = MAX_TAB_CONTROLS; // i.e. "no tab" else { if (*aParam3) // Which tab control. Must be processed prior to Param2 since it might change mCurrentTabControlIndex. { index = ATOI(aParam3) - 1; if (index < 0 || index > MAX_TAB_CONTROLS - 1) { result = ScriptError(ERR_PARAM3_INVALID ERR_ABORT, aParam3); goto return_the_result; } if (index != gui.mCurrentTabControlIndex) // This is checked early in case of early return in the next section due to error. { gui.mCurrentTabControlIndex = index; // Fix for v1.0.38.02: Changing to a different tab control (or none at all when there // was one before, or vice versa) should start a new radio group: gui.mInRadioGroup = false; } } if (*aParam2) // Index or name of a particular tab inside a control. { if (!*aParam3 && gui.mCurrentTabControlIndex == MAX_TAB_CONTROLS) // Provide a default: the most recently added tab control. If there are no // tab controls, assume the index is the first tab control (i.e. a tab control // to be created in the future). Fix for v1.0.46.16: This section must be done // prior to gui.FindTabControl() below because otherwise, a script that does // "Gui Tab" will find that a later use of "Gui Tab, TabName" won't work unless // the third parameter (which tab control) is explicitly specified. gui.mCurrentTabControlIndex = gui.mTabControlCount ? gui.mTabControlCount - 1 : 0; bool exact_match = !_tcsicmp(aParam4, _T("Exact")); // v1.0.37.03. // Unlike "GuiControl, Choose", in this case, don't allow negatives since that would just // generate an error msg further below: if (!exact_match && IsPureNumeric(aParam2, false, false)) { index = ATOI(aParam2) - 1; if (index < 0 || index > MAX_TABS_PER_CONTROL - 1) { result = ScriptError(ERR_PARAM2_INVALID ERR_ABORT, aParam2); goto return_the_result; } } else { index = -1; // Set default to be "failure". GuiControlType *tab_control = gui.FindTabControl(gui.mCurrentTabControlIndex); if (tab_control) index = gui.FindTabIndexByName(*tab_control, aParam2, exact_match); // Returns -1 on failure. if (index == -1) { result =ScriptError(_T("Tab name doesn't exist yet.") ERR_ABORT, aParam2); goto return_the_result; } } gui.mCurrentTabIndex = index; } if (gui.mCurrentTabIndex != prev_tab_index || gui.mCurrentTabControlIndex != prev_tab_control_index) gui.mInRadioGroup = false; // A fix for v1.0.38.02, see comments at similar line above. } goto return_the_result; } case GUI_CMD_COLOR: // AssignColor() takes care of deleting old brush, etc. // In this case, a blank for either param means "leaving existing color alone", in which // case AssignColor() is not called since it would assume CLR_NONE then. if (*aParam2) AssignColor(aParam2, gui.mBackgroundColorWin, gui.mBackgroundBrushWin); if (*aParam3) { AssignColor(aParam3, gui.mBackgroundColorCtl, gui.mBackgroundBrushCtl); // As documented, the following is not done. Primary reasons: // 1) Allows any custom color that was explicitly specified via "Gui, Add, ListView, BackgroundGreen" // to stay in effect rather than being overridden by this change. You could argue that this // could be detected by asking the control its background color and if it matches the previous // mBackgroundColorCtl (which might be CLR_DEFAULT?), it's 99% likely it was not an // individual/explicit custom color and thus should be changed here. But that would be even // more complexity so it seems better to keep it simple. // 2) Reduce code size. //for (GuiIndexType u = 0; u < gui.mControlCount; ++u) // if (gui.mControl[u].type == GUI_CONTROL_LISTVIEW && ListView_GetTextBkColor(..) != prev_bk_color_ctl) // { // ListView_SetTextBkColor(gui.mControl[u].hwnd, gui.mBackgroundColorCtl); // ListView_SetBkColor(gui.mControl[u].hwnd, gui.mBackgroundColorCtl); // } // ... and probably similar for TREEVIEW. } if (IsWindowVisible(gui.mHwnd)) // Force the window to repaint so that colors take effect immediately. // UpdateWindow() isn't enough sometimes/always, so do something more aggressive: InvalidateRect(gui.mHwnd, NULL, TRUE); goto return_the_result; case GUI_CMD_FLASH: // Note that FlashWindowEx() would have to be loaded dynamically since it is not available // on Win9x/NT. But for now, just this simple method is provided. In the future, more // sophisticated parameters can be made available to flash the window a given number of times // and at a certain frequency, and other options such as only-taskbar-button or only-caption. // Set FlashWindowEx() for more ideas: FlashWindow(gui.mHwnd, _tcsicmp(aParam2, _T("Off")) ? TRUE : FALSE); goto return_the_result; } // switch() result = FAIL; // Should never be reached, but avoids compiler warning and improves bug detection. return_the_result: DEPRIVATIZE_S_DEREF_BUF; return result; } ResultType Line::GuiControl(LPTSTR aCommand, LPTSTR aControlID, LPTSTR aParam3) { GuiType *pgui = Script::ResolveGui(aCommand, aCommand); GuiControlCmds guicontrol_cmd = Line::ConvertGuiControlCmd(aCommand); if (guicontrol_cmd == GUICONTROL_CMD_INVALID) // This is caught at load-time 99% of the time and can only occur here if the sub-command name // or Gui name is contained in a variable reference. Since it's so rare, the handling of it is // debatable, but to keep it simple just set ErrorLevel: return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); if (!pgui) // This departs from the tradition used by PerformGui() but since this type of error is rare, // and since use ErrorLevel adds a little bit of flexibility (since the script's current thread // is not unconditionally aborted), this seems best: return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); GuiType &gui = *pgui; // For performance. GuiIndexType control_index = gui.FindControl(aControlID); if (control_index >= gui.mControlCount) // Not found. return g_ErrorLevel->Assign(ERRORLEVEL_ERROR); GuiControlType &control = gui.mControl[control_index]; // For performance and convenience. // Beyond this point, errors are rare so set the default to "no error": g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Fixed for v1.0.48.04: Some operations on a GUI control can trigger a callback or OnMessage function; // e.g. SendMessage(control.hwnd, STM_SETIMAGE, ...). Such a function is then likely to change the contents // of the deref buffer, which would then alter the contents of the parameters used by commands like // GuiControl. To prevent that, make the current deref buffer private until this function returns. That // forces any newly launched callback or OnMessage function to create a new deref buffer if it needs one. // The main alternative to this method is to make copies of all the parameters and point the parameters to // the copies. But since the parameters might be very large, that method could perform much worse and would // be more complicated, especially since 99.9% of the time, the copies would turn out to be unnecessary // because the action doesn't wind up triggering any callback or OnMessage function. PRIVATIZE_S_DEREF_BUF; ResultType result = OK; // Set default return value for use with all instances of "goto" further below. // EVERYTHING below this point should use "result" and "goto return_the_result" instead of "return". LPTSTR malloc_buf; RECT rect; WPARAM checked; GuiControlType *tab_control; int new_pos; SYSTEMTIME st[2]; int selection_index; bool do_redraw_if_in_tab = false; bool do_redraw_unconditionally = false; switch (guicontrol_cmd) { case GUICONTROL_CMD_OPTIONS: { GuiControlOptionsType go; // Its contents not currently used here, but it might be in the future. gui.ControlInitOptions(go, control); result = gui.ControlParseOptions(aCommand, go, control, control_index); goto return_the_result; } case GUICONTROL_CMD_CONTENTS: case GUICONTROL_CMD_TEXT: switch (control.type) { case GUI_CONTROL_TEXT: case GUI_CONTROL_GROUPBOX: do_redraw_unconditionally = (control.attrib & GUI_CONTROL_ATTRIB_BACKGROUND_TRANS); // v1.0.40.01.
tinku99/ahkdll
89e9a00f248e5c34305076c2e730dc3d8e18585c
Fixed script storage and freeing
diff --git a/source/exports.cpp b/source/exports.cpp index a8e55e3..14920a5 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,751 +1,751 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} __int64 com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} unsigned int com_ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} __int64 com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC unsigned int com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL unsigned int com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} unsigned int com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT __int64 ahkFindFunc(LPTSTR funcname) { return (__int64)g_script.FindFunc(funcname); } EXPORT __int64 ahkFindLabel(LPTSTR aLabelName) { return (__int64)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT unsigned int ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (unsigned int)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (unsigned int) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount>aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } if (g_Warn_LocalSameAsGlobal) { // Scan all "automatic" local vars and warn the user if there are any with the same // name as a global variable, since that would probably indicate a missing declaration: int i, j; Func *func; for (i = aFuncCount; i < g_script.mFuncCount; ++i) { if (!(func = g_script.mFunc[i])->mIsBuiltIn) { for (j = 0; j < func->mVarCount; ++j) g_script.MaybeWarnLocalSameAsGlobal(func, func->mVar[j]); for (j = 0; j < func->mLazyVarCount; ++j) g_script.MaybeWarnLocalSameAsGlobal(func, func->mLazyVar[j]); } } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } - free(Line::sSourceFile[Line::sSourceFileCount]); + free(Line::sSourceFile[Line::sSourceFileCount - 1]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. AssignVariant(*aFunc->mParam[1].var, param2, false); if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 { AssignVariant(*aFunc->mParam[2].var, param3, false); if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 { AssignVariant(*aFunc->mParam[3].var, param4, false); if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 { AssignVariant(*aFunc->mParam[4].var, param5, false); if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 { AssignVariant(*aFunc->mParam[5].var, param6, false); if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 { AssignVariant(*aFunc->mParam[6].var, param7, false); if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 { AssignVariant(*aFunc->mParam[7].var, param8, false); if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 { AssignVariant(*aFunc->mParam[8].var, param9, false); if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 { AssignVariant(*aFunc->mParam[9].var, param10, false); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/script.cpp b/source/script.cpp index 36ea6f4..ce13df8 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1165,1025 +1165,1025 @@ LineNumberType Script::LoadFromText(LPTSTR aScript) mIsReadyToExecute = mAutoExecSectionIsRunning = false; // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedText(aScript) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { #ifndef MINIDLL // Check for any unprocessed #if expressions: for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } if (g_Warn_LocalSameAsGlobal) { // Scan all "automatic" local vars and warn the user if there are any with the same // name as a global variable, since that would probably indicate a missing declaration: int i, j; Func *func; for (i = 0; i < mFuncCount; ++i) { if (!(func = mFunc[i])->mIsBuiltIn) { for (j = 0; j < func->mVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mVar[j]); for (j = 0; j < func->mLazyVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mLazyVar[j]); } } } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above calls. // Use FindOrAdd, not Add, because the user may already have added it simply by // referring to it in the script: if ( !(g_ErrorLevel = FindOrAddVar(_T("ErrorLevel"))) ) return LOADING_FAILED; // Error. Above already displayed it for us. // Initialize the var state to zero right before running anything in the script: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Initialize the random number generator: // Note: On 32-bit hardware, the generator module uses only 2506 bytes of static // data, so it doesn't seem worthwhile to put it in a class (so that the mem is // only allocated on first use of the generator). For v1.0.24, _ftime() is not // used since it could be as large as 0.5 KB of non-compressed code. A simple call to // GetSystemTimeAsFileTime() seems just as good or better, since it produces // a FILETIME, which is "the number of 100-nanosecond intervals since January 1, 1601." // Use the low-order DWORD since the high-order one rarely changes. If my calculations are correct, // the low-order 32-bits traverses its full 32-bit range every 7.2 minutes, which seems to make // using it as a seed superior to GetTickCount for most purposes. RESEED_RANDOM_GENERATOR; return TRUE; // Must be non-zero. // OBSOLETE: mLineCount was always non-zero at this point since above did AddLine(). //return mLineCount; // The count of runnable lines that were loaded, which might be zero. } #endif #ifdef AUTOHOTKEYSC UINT Script::LoadFromFile() #else UINT Script::LoadFromFile(bool aScriptWasNotspecified) #endif // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; if (!mFileSpec || !*mFileSpec) return LOADING_FAILED; #ifndef AUTOHOTKEYSC // When not in stand-alone mode, read an external script file. DWORD attr = GetFileAttributes(mFileSpec); if (attr == MAXDWORD) // File does not exist or lacking the authorization to get its attributes. { #ifdef MINIDLL return LOADING_FAILED; #endif TCHAR buf[MAX_PATH + 256]; if (aScriptWasNotspecified) // v1.0.46.09: Give a more descriptive prompt to help users get started. { sntprintf(buf, _countof(buf), _T("To help you get started, would you like to create a sample script in the My Documents folder?\n") _T("\n") _T("Press YES to create and display the sample script.\n") _T("Press NO to exit.\n")); } else // Mostly for backward compatibility, also prompt to create if an explicitly specified script doesn't exist. sntprintf(buf, _countof(buf), _T("The script file \"%s\" does not exist. Create it now?"), mFileSpec); int response = MsgBox(buf, MB_YESNO); if (response != IDYES) return 0; FILE *fp2 = _tfopen(mFileSpec, _T("a")); if (!fp2) { MsgBox(_T("Could not create file, perhaps because the current directory is read-only") _T(" or has insufficient permissions.")); return LOADING_FAILED; } _fputts( _T("; IMPORTANT INFO ABOUT GETTING STARTED: Lines that start with a\n") _T("; semicolon, such as this one, are comments. They are not executed.\n") _T("\n") _T("; This script has a special filename and path because it is automatically\n") _T("; launched when you run the program directly. Also, any text file whose\n") _T("; name ends in .ahk is associated with the program, which means that it\n") _T("; can be launched simply by double-clicking it. You can have as many .ahk\n") _T("; files as you want, located in any folder. You can also run more than\n") _T("; one .ahk file simultaneously and each will get its own tray icon.\n") _T("\n") _T("; SAMPLE HOTKEYS: Below are two sample hotkeys. The first is Win+Z and it\n") _T("; launches a web site in the default browser. The second is Control+Alt+N\n") _T("; and it launches a new Notepad window (or activates an existing one). To\n") _T("; try out these hotkeys, run AutoHotkey again, which will load this file.\n") _T("\n") _T("#z::Run www.autohotkey.com\n") _T("\n") _T("^!n::\n") _T("IfWinExist Untitled - Notepad\n") _T("\tWinActivate\n") _T("else\n") _T("\tRun Notepad\n") _T("return\n") _T("\n") _T("\n") _T("; Note: From now on whenever you run AutoHotkey directly, this script\n") _T("; will be loaded. So feel free to customize it to suit your needs.\n") _T("\n") _T("; Please read the QUICK-START TUTORIAL near the top of the help file.\n") _T("; It explains how to perform common automation tasks such as sending\n") _T("; keystrokes and mouse clicks. It also explains more about hotkeys.\n") , fp2); fclose(fp2); // One or both of the below would probably fail -- at least on Win95 -- if mFileSpec ever // has spaces in it (since it's passed as the entire param string). So enclose the filename // in double quotes. I don't believe the directory needs to be in double quotes since it's // a separate field within the CreateProcess() and ShellExecute() structures: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) { MsgBox(_T("Can't open script.")); // Short msg since so rare. return LOADING_FAILED; } // future: have it wait for the process to close, then try to open the script again: return 0; } #endif // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedFile(mFileSpec, false, false) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { // Check for any unprocessed #if expressions: #ifndef MINIDLL for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } if (g_Warn_LocalSameAsGlobal) { // Scan all "automatic" local vars and warn the user if there are any with the same // name as a global variable, since that would probably indicate a missing declaration: int i, j; Func *func; for (i = 0; i < mFuncCount; ++i) { if (!(func = mFunc[i])->mIsBuiltIn) { for (j = 0; j < func->mVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mVar[j]); for (j = 0; j < func->mLazyVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mLazyVar[j]); } } } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above calls. // Use FindOrAdd, not Add, because the user may already have added it simply by // referring to it in the script: if ( !(g_ErrorLevel = FindOrAddVar(_T("ErrorLevel"))) ) return LOADING_FAILED; // Error. Above already displayed it for us. // Initialize the var state to zero right before running anything in the script: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Initialize the random number generator: // Note: On 32-bit hardware, the generator module uses only 2506 bytes of static // data, so it doesn't seem worthwhile to put it in a class (so that the mem is // only allocated on first use of the generator). For v1.0.24, _ftime() is not // used since it could be as large as 0.5 KB of non-compressed code. A simple call to // GetSystemTimeAsFileTime() seems just as good or better, since it produces // a FILETIME, which is "the number of 100-nanosecond intervals since January 1, 1601." // Use the low-order DWORD since the high-order one rarely changes. If my calculations are correct, // the low-order 32-bits traverses its full 32-bit range every 7.2 minutes, which seems to make // using it as a seed superior to GetTickCount for most purposes. RESEED_RANDOM_GENERATOR; return TRUE; // Must be non-zero. // OBSOLETE: mLineCount was always non-zero at this point since above did AddLine(). //return mLineCount; // The count of runnable lines that were loaded, which might be zero. } bool IsFunction(LPTSTR aBuf, bool *aPendingFunctionHasBrace = NULL) // Helper function for LoadIncludedFile(). // Caller passes in an aBuf containing a candidate line such as "function(x, y)" // Caller has ensured that aBuf is rtrim'd. // Caller should pass NULL for aPendingFunctionHasBrace to indicate that function definitions (open-brace // on same line as function) are not allowed. When non-NULL *and* aBuf is a function call/def, // *aPendingFunctionHasBrace is set to true if a brace is present at the end, or false otherwise. // In addition, any open-brace is removed from aBuf in this mode. { LPTSTR action_end = StrChrAny(aBuf, EXPR_ALL_SYMBOLS EXPR_ILLEGAL_CHARS); // Can't be a function definition or call without an open-parenthesis as first char found by the above. // In addition, if action_end isn't NULL, that confirms that the string in aBuf prior to action_end contains // no spaces, tabs, colons, or equal-signs. As a result, it can't be: // 1) a hotstring, since they always start with at least one colon that would be caught immediately as // first-expr-char-is-not-open-parenthesis by the above. // 2) Any kind of math or assignment, such as var:=(x+y) or var+=(x+y). // The only things it could be other than a function call or function definition are: // Normal label that ends in single colon but contains an open-parenthesis prior to the colon, e.g. Label(x): // Single-line hotkey such as KeyName::MsgBox. But since '(' isn't valid inside KeyName, this isn't a concern. // In addition, note that it isn't necessary to check for colons that lie outside of quoted strings because // we're only interested in the first "word" of aBuf: If this is indeed a function call or definition, what // lies to the left of its first open-parenthesis can't contain any colons anyway because the above would // have caught it as first-expr-char-is-not-open-parenthesis. In other words, there's no way for a function's // opening parenthesis to occur after a legitimate/quoted colon or double-colon in its parameters. // v1.0.40.04: Added condition "action_end != aBuf" to allow a hotkey or remap or hotkey such as // such as "(::" to work even if it ends in a close-parenthesis such as "(::)" or "(::MsgBox )" if ( !(action_end && *action_end == '(' && action_end != aBuf && tcslicmp(aBuf, _T("IF"), action_end - aBuf) && tcslicmp(aBuf, _T("WHILE"), action_end - aBuf)) // v1.0.48.04: Recognize While() as loop rather than a function because many programmers are in the habit of writing while() and if(). || action_end[1] == ':' ) // v1.0.44.07: This prevents "$(::fn_call()" from being seen as a function-call vs. hotkey-with-call. For simplicity and due to rarity, omit_leading_whitespace() isn't called; i.e. assumes that the colon immediate follows the '('. return false; LPTSTR aBuf_last_char = action_end + _tcslen(action_end) - 1; // Above has already ensured that action_end is "(...". if (aPendingFunctionHasBrace) // Caller specified that an optional open-brace may be present at the end of aBuf. { if (*aPendingFunctionHasBrace = (*aBuf_last_char == '{')) // Caller has ensured that aBuf is rtrim'd. { *aBuf_last_char = '\0'; // For the caller, remove it from further consideration. aBuf_last_char = aBuf + rtrim(aBuf, aBuf_last_char - aBuf) - 1; // Omit trailing whitespace too. } } return *aBuf_last_char == ')'; // This last check avoids detecting a label such as "Label(x):" as a function. // Also, it seems best never to allow if(...) to be a function call, even if it's blank inside such as if(). // In addition, it seems best not to allow if(...) to ever be a function definition since such a function // could never be called as ACT_EXPRESSION since it would be seen as an IF-stmt instead. } inline LPTSTR IsClassDefinition(LPTSTR aBuf, bool &aHasOTB) { if (_tcsnicmp(aBuf, _T("Class"), 5) || !IS_SPACE_OR_TAB(aBuf[5])) // i.e. it's not "Class" followed by a space or tab. return NULL; LPTSTR class_name = omit_leading_whitespace(aBuf + 6); if (_tcschr(EXPR_ALL_SYMBOLS EXPR_ILLEGAL_CHARS, *class_name)) // It's probably something like "Class := GetClass()". return NULL; // Check for opening brace on same line: LPTSTR aBuf_last_char = class_name + _tcslen(class_name) - 1; if (aHasOTB = (*aBuf_last_char == '{')) // Caller has ensured that aBuf is rtrim'd. { *aBuf_last_char = '\0'; // For the caller, remove it from further consideration. rtrim(aBuf, aBuf_last_char - aBuf); // Omit trailing whitespace too. } // Validation of the name is left up to the caller, for simplicity. return class_name; } #ifndef AUTOHOTKEYSC ResultType Script::LoadIncludedText(LPTSTR aFileSpec) // Returns OK or FAIL. // 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 { if (!aFileSpec || !*aFileSpec) return FAIL; // Keep this var on the stack due to recursion, which allows newly created lines to be given the // correct file number even when some #include's have been encountered in the middle of the script: int source_file_index = Line::sSourceFileCount; if (Line::sSourceFileCount >= Line::sMaxSourceFiles) { int new_max; if (Line::sMaxSourceFiles) { new_max = 2*Line::sMaxSourceFiles; if (new_max > ABSOLUTE_MAX_SOURCE_FILES) new_max = ABSOLUTE_MAX_SOURCE_FILES; } else new_max = 100; // For simplicity and due to rarity of every needing to, expand by reallocating the array. // Use a temp var. because realloc() returns NULL on failure but leaves original block allocated. LPTSTR *realloc_temp = (LPTSTR *)realloc(Line::sSourceFile, new_max * sizeof(LPTSTR)); // If passed NULL, realloc() will do a malloc(). if (!realloc_temp) return ScriptError(ERR_OUTOFMEM); // Short msg since so rare. Line::sSourceFile = realloc_temp; Line::sMaxSourceFiles = new_max; } if (!source_file_index) // Since this is the first source file, it must be the main script file. Just point it to the // location of the filespec already dynamically allocated: Line::sSourceFile[source_file_index] = aFileSpec; else { - Line::sSourceFile[source_file_index] = (LPTSTR)malloc(_tcslen(aFileSpec)* sizeof(TCHAR)); + Line::sSourceFile[source_file_index] = (LPTSTR)malloc((_tcslen(aFileSpec)+1)* sizeof(TCHAR)); _tcscpy(Line::sSourceFile[source_file_index],aFileSpec); } // <buf> should be no larger than LINE_SIZE because some later functions rely upon that: TCHAR msg_text[MAX_PATH + 256], buf1[LINE_SIZE], buf2[LINE_SIZE], suffix[16], pending_buf[LINE_SIZE] = _T(""); LPTSTR buf = buf1, next_buf = buf2; // Oscillate between bufs to improve performance (avoids memcpy from buf2 to buf1). size_t buf_length, next_buf_length, suffix_length; bool pending_buf_has_brace; bool pending_buf_is_class; // True for class definition, false for function definition/call. ++Line::sSourceFileCount; includedtextbuf.mBuffer = aFileSpec; includedtextbuf.mLength = (DWORD)(_tcslen(aFileSpec) * sizeof(TCHAR)); includedtextbuf.mOwned = false; TextMem tmem, *fp = &tmem; // NOTE: Ahk2Exe strips off the UTF-8 BOM. //tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF16); tmem.Open(includedtextbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR #ifdef UNICODE , CP_UTF16 #endif ); // File is now open, read lines from it. #ifndef MINIDLL LPTSTR hotkey_flag, cp, cp1, action_end, hotstring_start, hotstring_options; Hotkey *hk; #else LPTSTR hotkey_flag, cp, cp1, action_end; #endif LineNumberType pending_buf_line_number, saved_line_number; #ifndef MINIDLL HookActionType hook_action; bool is_label, suffix_has_tilde, hook_is_mandatory, in_comment_section, hotstring_options_all_valid; #else bool is_label, in_comment_section; #endif #ifndef MINIDLL // For the remap mechanism, e.g. a::b int remap_stage; vk_type remap_source_vk, remap_dest_vk = 0; // Only dest is initialized to enforce the fact that it is the flag/signal to indicate whether remapping is in progress. TCHAR remap_source[32], remap_dest[32], remap_dest_modifiers[8]; // Must fit the longest key name (currently Browser_Favorites [17]), but buffer overflow is checked just in case. LPTSTR extra_event; bool remap_source_is_mouse, remap_dest_is_mouse, remap_keybd_to_mouse; #endif // For the line continuation mechanism: bool do_ltrim, do_rtrim, literal_escapes, literal_derefs, literal_delimiters , has_continuation_section, is_continuation_line; #define CONTINUATION_SECTION_WITHOUT_COMMENTS 1 // MUST BE 1 because it's the default set by anything that's boolean-true. #define CONTINUATION_SECTION_WITH_COMMENTS 2 // Zero means "not in a continuation section". int in_continuation_section; LPTSTR next_option, option_end; TCHAR orig_char, one_char_string[2], two_char_string[3]; // Line continuation mechanism's option parsing. one_char_string[1] = '\0'; // Pre-terminate these to simplify code later below. two_char_string[2] = '\0'; // int continuation_line_count; #define MAX_FUNC_VAR_EXCEPTIONS 2000 Var *func_exception_var[MAX_FUNC_VAR_EXCEPTIONS]; // Init both for main file and any included files loaded by this function: mCurrFileIndex = source_file_index; // source_file_index is kept on the stack due to recursion (from #include). LineNumberType phys_line_number = 0; buf_length = GetLine(buf, LINE_SIZE - 1, 0, fp); if (in_comment_section = !_tcsncmp(buf, _T("/*"), 2)) { // Fixed for v1.0.35.08. Must reset buffer to allow a script's first line to be "/*". *buf = '\0'; buf_length = 0; } while (buf_length != -1) // Compare directly to -1 since length is unsigned. { // For each whole line (a line with continuation section is counted as only a single line // for the purpose of this outer loop). // Keep track of this line's *physical* line number within its file for A_LineNumber and // error reporting purposes. This must be done only in the outer loop so that it tracks // the topmost line of any set of lines merged due to continuation section/line(s).. mCombinedLineNumber = phys_line_number + 1; // This must be reset for each iteration because a prior iteration may have changed it, even // indirectly by calling something that changed it: mCurrLine = NULL; // To signify that we're in transition, trying to load a new one. // v1.0.44.13: An additional call to IsDirective() is now made up here so that #CommentFlag affects // the line beneath it the same way as other lines (#EscapeChar et. al. didn't have this bug). // It's best not to process ALL directives up here because then they would no longer support a // continuation section beneath them (and possibly other drawbacks because it was never thoroughly // tested). if (!_tcsnicmp(buf, _T("#CommentFlag"), 12)) // Have IsDirective() process this now (it will also process it again later, which is harmless). if (IsDirective(buf) == FAIL) // IsDirective() already displayed the error. return FAIL; // Read in the next line (if that next line is the start of a continuation section, append // it to the line currently being processed: for (has_continuation_section = false, in_continuation_section = 0;;) { // This increment relies on the fact that this loop always has at least one iteration: ++phys_line_number; // Tracks phys. line number in *this* file (independent of any recursion caused by #Include). next_buf_length = GetLine(next_buf, LINE_SIZE - 1, in_continuation_section, fp); if (next_buf_length && next_buf_length != -1 // Prevents infinite loop when file ends with an unclosed "/*" section. Compare directly to -1 since length is unsigned. && !in_continuation_section) // Multi-line comments can't be used in continuation sections. This line fixes '*/' being discarded in continuation sections (broken by L54). { if (!_tcsncmp(next_buf, _T("*/"), 2) // Check this even if !in_comment_section so it can be ignored (for convenience) and not treated as a line-continuation operator. && (in_comment_section || next_buf[2] != ':' || next_buf[3] != ':')) // ...but support */:: as a hotkey. { in_comment_section = false; next_buf_length -= 2; // Adjust for removal of /* from the beginning of the string. tmemmove(next_buf, next_buf + 2, next_buf_length + 1); // +1 to include the string terminator. next_buf_length = ltrim(next_buf, next_buf_length); // Get rid of any whitespace that was between the comment-end and remaining text. if (!*next_buf) // The rest of the line is empty, so it was just a naked comment-end. continue; } else if (in_comment_section) continue; if (!_tcsncmp(next_buf, _T("/*"), 2)) { in_comment_section = true; continue; // It's now commented out, so the rest of this line is ignored. } } if (in_comment_section) // Above has incremented and read the next line, which is everything needed while inside /* .. */ { if (next_buf_length == -1) // Compare directly to -1 since length is unsigned. break; // By design, it's not an error. This allows "/*" to be used to comment out the bottommost portion of the script without needing a matching "*/". // Otherwise, continue reading lines so that they can be merged with the line above them // if they qualify as continuation lines. continue; } if (!in_continuation_section) // This is either the first iteration or the line after the end of a previous continuation section. { // v1.0.38.06: The following has been fixed to exclude "(:" and "(::". These should be // labels/hotkeys, not the start of a continuation section. In addition, a line that starts // with '(' but that ends with ':' should be treated as a label because labels such as // "(label):" are far more common than something obscure like a continuation section whose // join character is colon, namely "(Join:". if ( !(in_continuation_section = (next_buf_length != -1 && *next_buf == '(' // Compare directly to -1 since length is unsigned. && next_buf[1] != ':' && next_buf[next_buf_length - 1] != ':')) ) // Relies on short-circuit boolean order. { if (next_buf_length == -1) // Compare directly to -1 since length is unsigned. break; if (!next_buf_length) // It is permitted to have blank lines and comment lines in between the line above // and any continuation section/line that might come after the end of the // comment/blank lines: continue; // SINCE ABOVE DIDN'T BREAK/CONTINUE, NEXT_BUF IS NON-BLANK. if (next_buf[next_buf_length - 1] == ':' && *next_buf != ',') // With the exception of lines starting with a comma, the last character of any // legitimate continuation line can't be a colon because expressions can't end // in a colon. The only exception is the ternary operator's colon, but that is // very rare because it requires the line after it also be a continuation line // or section, which is unusual to say the least -- so much so that it might be // too obscure to even document as a known limitation. Anyway, by excluding lines // that end with a colon from consideration ambiguity with normal labels // and non-single-line hotkeys and hotstrings is eliminated. break; is_continuation_line = false; // Set default. switch(ctoupper(*next_buf)) // Above has ensured *next_buf != '\0' (toupper might have problems with '\0'). { case 'A': // "AND". // See comments in the default section further below. if (!_tcsnicmp(next_buf, _T("and"), 3) && IS_SPACE_OR_TAB_OR_NBSP(next_buf[3])) // Relies on short-circuit boolean order. { cp = omit_leading_whitespace(next_buf + 3); // v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS // to properly detect a continuation line whose first char after AND/OR is "!~*&-+()": if (!_tcschr(EXPR_CORE, *cp)) // This check recognizes the following examples as NON-continuation lines by checking // that AND/OR aren't followed immediately by something that's obviously an operator: // and := x, and = 2 (but not and += 2 since the an operand can have a unary plus/minus). // This is done for backward compatibility. Also, it's documented that // AND/OR/NOT aren't supported as variable names inside expressions. is_continuation_line = true; // Override the default set earlier. } break; case 'O': // "OR". // See comments in the default section further below. if (ctoupper(next_buf[1]) == 'R' && IS_SPACE_OR_TAB_OR_NBSP(next_buf[2])) // Relies on short-circuit boolean order. { cp = omit_leading_whitespace(next_buf + 2); // v1.0.38.06: The following was fixed to use EXPR_CORE vs. EXPR_OPERAND_TERMINATORS // to properly detect a continuation line whose first char after AND/OR is "!~*&-+()": if (!_tcschr(EXPR_CORE, *cp)) // See comment in the "AND" case above. is_continuation_line = true; // Override the default set earlier. } break; default: // Desired line continuation operators: // Pretty much everything, namely: // +, -, *, /, //, **, <<, >>, &, |, ^, <, >, <=, >=, =, ==, <>, !=, :=, +=, -=, /=, *=, ?, : // And also the following remaining unaries (i.e. those that aren't also binaries): !, ~ // The first line below checks for ::, ++, and --. Those can't be continuation lines because: // "::" isn't a valid operator (this also helps performance if there are many hotstrings). // ++ and -- are ambiguous with an isolated line containing ++Var or --Var (and besides, // wanting to use ++ to continue an expression seems extremely rare, though if there's ever // demand for it, might be able to look at what lies to the right of the operator's operand // -- though that would produce inconsistent continuation behavior since ++Var itself still // could never be a continuation line due to ambiguity). // // The logic here isn't smart enough to differentiate between a leading ! or - that's // meant as a continuation character and one that isn't. Even if it were, it would // still be ambiguous in some cases because the author's intent isn't known; for example, // the leading minus sign on the second line below is ambiguous, so will probably remain // a continuation character in both v1 and v2: // x := y // -z ? a:=1 : func() if ((*next_buf == ':' || *next_buf == '+' || *next_buf == '-') && next_buf[1] == *next_buf // See above. // L31: '.' and '?' no longer require spaces; '.' without space is member-access (object) operator. //|| (*next_buf == '.' || *next_buf == '?') && !IS_SPACE_OR_TAB_OR_NBSP(next_buf[1]) // The "." and "?" operators require a space or tab after them to be legitimate. For ".", this is done in case period is ever a legal character in var names, such as struct support. For "?", it's done for backward compatibility since variable names can contain question marks (though "?" by itself is not considered a variable in v1.0.46). //&& next_buf[1] != '=' // But allow ".=" (and "?=" too for code simplicity), since ".=" is the concat-assign operator. || !_tcschr(CONTINUATION_LINE_SYMBOLS, *next_buf)) // Line doesn't start with a continuation char. break; // Leave is_continuation_line set to its default of false. // Some of the above checks must be done before the next ones. if ( !(hotkey_flag = _tcsstr(next_buf, HOTKEY_FLAG)) ) // Without any "::", it can't be a hotkey or hotstring. { is_continuation_line = true; // Override the default set earlier. break; } #ifndef MINIDLL if (*next_buf == ':') // First char is ':', so it's more likely a hotstring than a hotkey. { // Remember that hotstrings can contain what *appear* to be quoted literal strings, // so detecting whether a "::" is in a quoted/literal string in this case would // be more complicated. That's one reason this other method is used. for (hotstring_options_all_valid = true, cp = next_buf + 1; *cp && *cp != ':'; ++cp) if (!IS_HOTSTRING_OPTION(*cp)) // Not a perfect test, but eliminates most of what little remaining ambiguity exists between ':' as a continuation character vs. ':' as the start of a hotstring. It especially eliminates the ":=" operator. { hotstring_options_all_valid = false; break; } if (hotstring_options_all_valid && *cp == ':') // It's almost certainly a hotstring. break; // So don't treat it as a continuation line. //else it's not a hotstring but it might still be a hotkey such as ": & x::". // So continue checking below. } #endif // Since above didn't "break", this line isn't a hotstring but it is probably a hotkey // because above already discovered that it contains "::" somewhere. So try to find out // if there's anything that disqualifies this from being a hotkey, such as some // expression line that contains a quoted/literal "::" (or a line starting with // a comma that contains an unquoted-but-literal "::" such as for FileAppend). if (*next_buf == ',') { cp = omit_leading_whitespace(next_buf + 1); // The above has set cp to the position of the non-whitespace item to the right of // this comma. Normal (single-colon) labels can't contain commas, so only hotkey // labels are sources of ambiguity. In addition, normal labels and hotstrings have // already been checked for, higher above. #ifndef MINIDLL if ( _tcsncmp(cp, HOTKEY_FLAG, HOTKEY_FLAG_LENGTH) // It's not a hotkey such as ",::action". && _tcsncmp(cp - 1, COMPOSITE_DELIMITER, COMPOSITE_DELIMITER_LENGTH) ) // ...and it's not a hotkey such as ", & y::action". #endif is_continuation_line = true; // Override the default set earlier. } else // First symbol in line isn't a comma but some other operator symbol. { // Check if the "::" found earlier appears to be inside a quoted/literal string. // This check is NOT done for a line beginning with a comma since such lines // can contain an unquoted-but-literal "::". In addition, this check is done this // way to detect hotkeys such as the following: // +keyname:: (and other hotkey modifier symbols such as ! and ^) // +keyname1 & keyname2:: // +^:: (i.e. a modifier symbol followed by something that is a hotkey modiefer and/or a hotkey suffix and/or an expression operator). // <:: and &:: (i.e. hotkeys that are also expression-continuation symbols) // By contrast, expressions that qualify as continuation lines can look like: // . "xxx::yyy" // + x . "xxx::yyy" // In addition, hotkeys like the following should continue to be supported regardless // of how things are done here: // ^":: // . & ":: // Finally, keep in mind that an expression-continuation line can start with two // consecutive unary operators like !! or !*. It can also start with a double-symbol // operator such as <=, <>, !=, &&, ||, //, **. for (cp = next_buf; cp < hotkey_flag && *cp != '"'; ++cp); if (cp == hotkey_flag) // No '"' found to left of "::", so this "::" appears to be a real hotkey flag rather than part of a literal string. break; // Treat this line as a normal line vs. continuation line. for (cp = hotkey_flag + HOTKEY_FLAG_LENGTH; *cp && *cp != '"'; ++cp); if (*cp) { // Closing quote was found so "::" is probably inside a literal string of an // expression (further checking seems unnecessary given the fairly extreme // rarity of using '"' as a key in a hotkey definition). is_continuation_line = true; // Override the default set earlier. } //else no closing '"' found, so this "::" probably belongs to something like +":: or // . & "::. Treat this line as a normal line vs. continuation line. } } // switch(toupper(*next_buf)) if (is_continuation_line) { if (buf_length + next_buf_length >= LINE_SIZE - 1) // -1 to account for the extra space added below. return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, next_buf); if (*next_buf != ',') // Insert space before expression operators so that built/combined expression works correctly (some operators like 'and', 'or', '.', and '?' currently require spaces on either side) and also for readability of ListLines. buf[buf_length++] = ' '; tmemcpy(buf + buf_length, next_buf, next_buf_length + 1); // Append this line to prev. and include the zero terminator. buf_length += next_buf_length; continue; // Check for yet more continuation lines after this one. } // Since above didn't continue, there is no continuation line or section. In addition, // since this line isn't blank, no further searching is needed. break; } // if (!in_continuation_section) // OTHERWISE in_continuation_section != 0, so the above has found the first line of a new // continuation section. continuation_line_count = 0; // Reset for this new section. // Otherwise, parse options. First set the defaults, which can be individually overridden // by any options actually present. RTrim defaults to ON for two reasons: // 1) Whitespace often winds up at the end of a lines in a text editor by accident. In addition, // whitespace at the end of any consolidated/merged line will be rtrim'd anyway, since that's // how command parsing works. // 2) Copy & paste from the forum and perhaps other web sites leaves a space at the end of each // line. Although this behavior is probably site/browser-specific, it's a consideration. do_ltrim = g_ContinuationLTrim; // Start off at global default. do_rtrim = true; // Seems best to rtrim even if this line is a hotstring, since it is very rare that trailing spaces and tabs would ever be desirable. // For hotstrings (which could be detected via *buf==':'), it seems best not to default the // escape character (`) to be literal because the ability to have `t `r and `n inside the // hotstring continuation section seems more useful/common than the ability to use the // accent character by itself literally (which seems quite rare in most languages). literal_escapes = false; literal_derefs = false; literal_delimiters = true; // This is the default even for hotstrings because although using (*buf != ':') would improve loading performance, it's not a 100% reliable way to detect hotstrings. // The default is linefeed because: // 1) It's the best choice for hotstrings, for which the line continuation mechanism is well suited. // 2) It's good for FileAppend. // 3) Minor: Saves memory in large sections by being only one character instead of two. suffix[0] = '\n'; suffix[1] = '\0'; suffix_length = 1; for (next_option = omit_leading_whitespace(next_buf + 1); *next_option; next_option = omit_leading_whitespace(option_end)) { // 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. // Temporarily terminate to help eliminate ambiguity for words contained inside other words, // such as hypothetical "Checked" inside of "CheckedGray": orig_char = *option_end; *option_end = '\0'; if (!_tcsnicmp(next_option, _T("Join"), 4)) { next_option += 4; tcslcpy(suffix, next_option, _countof(suffix)); // The word "Join" by itself will product an empty string, as documented. // Passing true for the last parameter supports `s as the special escape character, // which allows space to be used by itself and also at the beginning or end of a string // containing other chars. ConvertEscapeSequences(suffix, g_EscapeChar, true); suffix_length = _tcslen(suffix); } else if (!_tcsnicmp(next_option, _T("LTrim"), 5)) do_ltrim = (next_option[5] != '0'); // i.e. Only an explicit zero will turn it off. else if (!_tcsnicmp(next_option, _T("RTrim"), 5)) do_rtrim = (next_option[5] != '0'); else { // Fix for v1.0.36.01: Missing "else" above, because otherwise, the option Join`r`n // would be processed above but also be processed again below, this time seeing the // accent and thinking it's the signal to treat accents literally for the entire // continuation section rather than as escape characters. // Within this terminated option substring, allow the characters to be adjacent to // improve usability: for (; *next_option; ++next_option) { switch (*next_option) { case '`': // Although not using g_EscapeChar (reduces code size/complexity), #EscapeChar is still supported by continuation sections; it's just that enabling the option uses '`' rather than the custom escape-char (one reason is that that custom escape-char might be ambiguous with future/past options if it's something weird like an alphabetic character). literal_escapes = true; break; case '%': // Same comment as above. literal_derefs = true; break; case ',': // Same comment as above. literal_delimiters = false; break; case 'C': // v1.0.45.03: For simplicity, anything that begins with "C" is enough to case 'c': // identify it as the option to allow comments in the section. in_continuation_section = CONTINUATION_SECTION_WITH_COMMENTS; // Override the default, which is boolean true (i.e. 1). break; case ')': // Probably something like (x.y)[z](), which is not intended as the beginning of // a continuation section. Doing this only when ")" is found should remove the // need to escape "(" in most real-world expressions while still allowing new // options to be added later with minimal risk of breaking scripts. in_continuation_section = 0; *option_end = orig_char; // Undo the temporary termination. goto process_completed_line; } } } // If the item was not handled by the above, ignore it because it is unknown. *option_end = orig_char; // Undo the temporary termination. } // for() each item in option list // "has_continuation_section" indicates whether the line we're about to construct is partially // composed of continuation lines beneath it. It's separate from continuation_line_count // in case there is another continuation section immediately after/adjacent to the first one, // but the second one doesn't have any lines in it: has_continuation_section = true; continue; // Now that the open-parenthesis of this continuation section has been processed, proceed to the next line. } // if (!in_continuation_section) // Since above didn't "continue", we're in the continuation section and thus next_buf contains // either a line to be appended onto buf or the closing parenthesis of this continuation section. if (next_buf_length == -1) // Compare directly to -1 since length is unsigned. return ScriptError(ERR_MISSING_CLOSE_PAREN, buf); if (next_buf_length == -2) // v1.0.45.03: Special flag that means "this is a commented-out line to be continue; // entirely omitted from the continuation section." Compare directly to -2 since length is unsigned. if (*next_buf == ')') { in_continuation_section = 0; // Facilitates back-to-back continuation sections and proper incrementing of phys_line_number. next_buf_length = rtrim(next_buf); // Done because GetLine() wouldn't have done it due to have told it we're in a continuation section. // Anything that lies to the right of the close-parenthesis gets appended verbatim, with // no trimming (for flexibility) and no options-driven translation: cp = next_buf + 1; // Use temp var cp to avoid altering next_buf (for maintainability). --next_buf_length; // This is now the length of cp, not next_buf. } else { cp = next_buf; // The following are done in this block only because anything that comes after the closing // parenthesis (i.e. the block above) is exempt from translations and custom trimming. // This means that commas are always delimiters and percent signs are always deref symbols // in the previous block. if (do_rtrim) next_buf_length = rtrim(next_buf, next_buf_length); if (do_ltrim) next_buf_length = ltrim(next_buf, next_buf_length); // Escape each comma and percent sign in the body of the continuation section so that // the later parsing stages will see them as literals. Although, it's not always // necessary to do this (e.g. commas in the last parameter of a command don't need to // be escaped, nor do percent signs in hotstrings' auto-replace text), the settings // are applied unconditionally because: // 1) Determining when its safe to omit the translation would add a lot of code size and complexity. // 2) The translation doesn't affect the functionality of the script since escaped literals // are always de-escaped at a later stage, at least for everything that's likely to matter // or that's reasonable to put into a continuation section (e.g. a hotstring's replacement text). // UPDATE for v1.0.44.11: #EscapeChar, #DerefChar, #Delimiter are now supported by continuation // sections because there were some requests for that in forum. int replacement_count = 0; if (literal_escapes) // literal_escapes must be done FIRST because otherwise it would also replace any accents added for literal_delimiters or literal_derefs. { one_char_string[0] = g_EscapeChar; // These strings were terminated earlier, so no need to two_char_string[0] = g_EscapeChar; // do it here. In addition, these strings must be set by two_char_string[1] = g_EscapeChar; // each iteration because the #EscapeChar (and similar directives) can occur multiple times, anywhere in the script. replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } if (literal_derefs) { one_char_string[0] = g_DerefChar; two_char_string[0] = g_EscapeChar; two_char_string[1] = g_DerefChar; replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } if (literal_delimiters) { one_char_string[0] = g_delimiter; two_char_string[0] = g_EscapeChar; two_char_string[1] = g_delimiter; replacement_count += StrReplace(next_buf, one_char_string, two_char_string, SCS_SENSITIVE, UINT_MAX, LINE_SIZE); } if (replacement_count) // Update the length if any actual replacements were done. next_buf_length = _tcslen(next_buf); } // Handling of a normal line within a continuation section. // Must check the combined length only after anything that might have expanded the string above. if (buf_length + next_buf_length + suffix_length >= LINE_SIZE) return ScriptError(ERR_CONTINUATION_SECTION_TOO_LONG, cp); ++continuation_line_count; // Append this continuation line onto the primary line. // The suffix for the previous line gets written immediately prior writing this next line, // which allows the suffix to be omitted for the final line. But if this is the first line, // No suffix is written because there is no previous line in the continuation section. // In addition, cp!=next_buf, this is the special line whose text occurs to the right of the // continuation section's closing parenthesis. In this case too, the previous line doesn't // get a suffix. if (continuation_line_count > 1 && suffix_length && cp == next_buf) { tmemcpy(buf + buf_length, suffix, suffix_length + 1); // Append and include the zero terminator. buf_length += suffix_length; // Must be done only after the old value of buf_length was used above. } if (next_buf_length) {
tinku99/ahkdll
0cfbdf1a5f1b853eea91f5b3a5fdd24a7a903c17
Added FindLabel function and changed ahkFindLabel to return pointer to label not line
diff --git a/source/ComServer.idl b/source/ComServer.idl index e2424ae..7b54161 100644 --- a/source/ComServer.idl +++ b/source/ComServer.idl @@ -1,71 +1,71 @@ import "wtypes.idl"; [ uuid(A9863C65-8CD4-4069-893D-3B5A3DDFAE88), version(1.0) ] library LibCOMServer { importlib("stdole32.tlb"); importlib("stdole.tlb"); [ uuid(04FFE41B-8FE9-4479-990A-B186EC73F49C), dual, oleautomation ] interface ICOMServer : IDispatch { [id(1)] HRESULT ahktextdll([in,optional] VARIANT script,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] unsigned int* hThread); [id(2)] HRESULT ahkdll([in,optional] VARIANT filepath,[in,optional] VARIANT options,[in,optional] VARIANT params, [out, retval] unsigned int* hThread); [id(3)] HRESULT ahkPause([in,optional] VARIANT aChangeTo,[out, retval] BOOL* paused); [id(4)] HRESULT ahkReady([out, retval] BOOL* ready); - [id(5)] HRESULT ahkFindLabel([in] VARIANT aLabelName,[out, retval] unsigned int* pLabel); + [id(5)] HRESULT ahkFindLabel([in] VARIANT aLabelName,[out, retval] __int64 *pLabel); [id(6)] HRESULT ahkgetvar([in] VARIANT name,[in,optional] VARIANT getVar,[out, retval] VARIANT *returnVal); [id(7)] HRESULT ahkassign([in] VARIANT name,[in,optional] VARIANT value,[out, retval] unsigned int* success); [id(8)] HRESULT ahkExecuteLine([in,optional] VARIANT line,[in,optional] VARIANT aMode,[in,optional] VARIANT wait,[out, retval] unsigned int* pLine); [id(9)] HRESULT ahkLabel([in] VARIANT aLabelName,[in,optional] VARIANT nowait,[out, retval] BOOL* success); - [id(10)] HRESULT ahkFindFunction([in] VARIANT FuncName,[out, retval] unsigned int* pFunc); + [id(10)] HRESULT ahkFindFunction([in] VARIANT FuncName,[out, retval] __int64 *pFunc); [id(11)] HRESULT ahkFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] VARIANT* returnVal); [id(12)] HRESULT ahkPostFunction([in] VARIANT FuncName,[in,optional] VARIANT param1,[in,optional] VARIANT param2,[in,optional] VARIANT param3,[in,optional] VARIANT param4,[in,optional] VARIANT param5,[in,optional] VARIANT param6,[in,optional] VARIANT param7,[in,optional] VARIANT param8,[in,optional] VARIANT param9,[in,optional] VARIANT param10,[out, retval] unsigned int* returnVal); [id(13)] HRESULT ahkKey([in] VARIANT name,[out, retval] BOOL* success); [id(14)] HRESULT addScript([in] VARIANT script,[in,optional] VARIANT replace,[out, retval] unsigned int* success); [id(15)] HRESULT addFile([in] VARIANT filepath,[in,optional] VARIANT aAllowDuplicateInclude,[in,optional] VARIANT aIgnoreLoadFailure,[out, retval] unsigned int* success); [id(16)] HRESULT ahkExec([in] VARIANT script,[out, retval] BOOL* success); [id(17)] HRESULT ahkTerminate([in,optional] VARIANT kill,[out, retval] BOOL* success); } [ uuid(C00BCC8C-5A04-4392-870F-20AAE1B926B2), helpstring("AutoHotkey Script") ] coclass CoCOMServer { [default] interface ICOMServer; } #ifdef _WIN64 [ uuid(38D00012-DC83-4E17-9BAD-D9DD97902580), helpstring("AutoHotkey Script X64") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else #ifdef _UNICODE [ uuid(C58DCD96-1D6F-4F85-B555-02B7F21F5CAF), helpstring("AutoHotkey Script UNICODE") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #else [ uuid(974318D9-A5B2-4FE5-8AC4-33A0C9EBB8B5), helpstring("AutoHotkey Script ANSI") ] coclass CoCOMServerOptional { [default] interface ICOMServer; } #endif //Unicode #endif //Win64 } diff --git a/source/ComServer_i.h b/source/ComServer_i.h index a518393..fc6de95 100644 --- a/source/ComServer_i.h +++ b/source/ComServer_i.h @@ -1,294 +1,294 @@ #ifdef _USRDLL #ifndef MINIDLL /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0555 */ /* at Sat Oct 09 20:41:58 2010 */ /* Compiler settings for automcomserver.idl: Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555 protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ /* @@MIDL_FILE_HEADING( ) */ #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __automcomserver_i_h__ #define __automcomserver_i_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ICOMServer_FWD_DEFINED__ #define __ICOMServer_FWD_DEFINED__ typedef interface ICOMServer ICOMServer; #endif /* __ICOMServer_FWD_DEFINED__ */ #ifndef __CoCOMServer_FWD_DEFINED__ #define __CoCOMServer_FWD_DEFINED__ #ifdef __cplusplus typedef class CoCOMServer CoCOMServer; #else typedef struct CoCOMServer CoCOMServer; #endif /* __cplusplus */ #endif /* __CoCOMServer_FWD_DEFINED__ */ /* header files for imported files */ #include "wtypes.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __LibCOMServer_LIBRARY_DEFINED__ #define __LibCOMServer_LIBRARY_DEFINED__ /* library LibCOMServer */ /* [version][uuid] */ DEFINE_GUID(LIBID_LibCOMServer,0xa9863c65, 0x8cd4, 0x4069, 0x89, 0x3d, 0x3b, 0x5a, 0x3d, 0xdf, 0xae, 0x88); #ifndef __ICOMServer_INTERFACE_DEFINED__ #define __ICOMServer_INTERFACE_DEFINED__ /* interface ICOMServer */ /* [object][oleautomation][dual][uuid] */ DEFINE_GUID(IID_ICOMServer,0x4ffe41b, 0x8fe9, 0x4479, 0x99, 0xa, 0xb1, 0x86, 0xec, 0x73, 0xf4, 0x9c); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("04FFE41B-8FE9-4479-990A-B186EC73F49C") ICOMServer : public IDispatch { public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahktextdll( /*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /* [retval][out] */unsigned int* hThread) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkdll( /*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params, /* [retval][out] */unsigned int* hThread) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkPause( /*in,optional*/VARIANT aChangeTo,/* [retval][out] */BOOL* paused) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkReady( /* [retval][out] */BOOL* ready) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFindLabel( - /*[in]*/ VARIANT aLabelName,/*[out, retval]*/ unsigned int* pLabel) = 0; + /*[in]*/ VARIANT aLabelName,/*[out, retval]*/ __int64 *pLabel) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkgetvar( /*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT getVar,/*[out, retval]*/ VARIANT *returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkassign( /*[in]*/ VARIANT name,/*[in,optional]*/ VARIANT value,/*[out, retval]*/ unsigned int* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkExecuteLine( /*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ unsigned int* pLine) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkLabel( /*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFindFunc( - /*[in]*/ VARIANT FuncName,/*[out, retval]*/ unsigned int* pFunc) = 0; + /*[in]*/ VARIANT FuncName,/*[out, retval]*/ __int64 *pFunc) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkFunction( /*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkPostFunction( /*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkKey( /*[in]*/ VARIANT name,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE addScript( /*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ unsigned int* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE addFile( /*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ unsigned int* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkExec( /*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) = 0; public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE ahkTerminate( /*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) = 0; }; #else /* C style interface */ typedef struct ICOMServerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ICOMServer * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ICOMServer * This); ULONG ( STDMETHODCALLTYPE *Release )( ICOMServer * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ICOMServer * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ICOMServer * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ICOMServer * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICOMServer * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); /* [id] */ HRESULT ( STDMETHODCALLTYPE *Name )( ICOMServer * This, /* [retval][out] */ BSTR *objectname); END_INTERFACE } ICOMServerVtbl; interface ICOMServer { CONST_VTBL struct ICOMServerVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICOMServer_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICOMServer_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICOMServer_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICOMServer_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICOMServer_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICOMServer_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICOMServer_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICOMServer_Name(This,objectname) \ ( (This)->lpVtbl -> Name(This,objectname) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICOMServer_INTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_CoCOMServer,0xc00bcc8c, 0x5a04, 0x4392, 0x87, 0xf, 0x20, 0xaa, 0xe1, 0xb9, 0x26, 0xb2); #ifdef _WIN64 DEFINE_GUID(CLSID_CoCOMServerOptioal,0x38D00012,0xDC83,0x4E17,0x9B,0xAD,0xD9,0xDD,0x97,0x90,0x25,0x80); #else #ifdef _UNICODE DEFINE_GUID(CLSID_CoCOMServerOptional,0xC58DCD96,0x1D6F,0x4F85,0xB5,0x55,0x02,0xB7,0xF2,0x1F,0x5C,0xAF); #else DEFINE_GUID(CLSID_CoCOMServerOptional,0x974318D9,0xA5B2,0x4FE5,0x8A,0xC4,0x33,0xA0,0xC9,0xEB,0xB8,0xB5); #endif #endif #ifdef __cplusplus class DECLSPEC_UUID("C00BCC8C-5A04-4392-870F-20AAE1B926B2") CoCOMServer; #ifdef _WIN64 class DECLSPEC_UUID("38D00012-DC83-4E17-9BAD-D9DD97902580") #else #ifdef _UNICODE class DECLSPEC_UUID("C58DCD96-1D6F-4F85-B555-02B7F21F5CAF") #else class DECLSPEC_UUID("974318D9-A5B2-4FE5-8AC4-33A0C9EBB8B5") #endif #endif CoCOMServerOptional; #endif #endif /* __LibCOMServer_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif #endif #endif \ No newline at end of file diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 3b99364..de7aa55 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -210,909 +210,909 @@ int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCm } else { g_DebuggerHost = "127.0.0.1"; g_DebuggerPort = "9000"; } // The actual debug session is initiated after the script is successfully parsed. } #endif else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design). { switch_processing_is_complete = true; // No more switches allowed after this point. break; // No more switches allowed after this point. } } if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptParams; A_ScriptParams = g_script.FindOrAddVar(_T("A_ScriptParams")); A_ScriptParams->Assign(nameHinstanceP.args); Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,(bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = !nameHinstanceP.istext ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef _USRDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #else #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #endif #endif #ifndef MINIDLL /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } #ifdef CONFIG_DEBUGGER // Initiate debug session now if applicable. if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK) { g_Debugger.ProcessCommands(); } #endif // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(bool kill) { int lpExitCode = 0; g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if (!kill) for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < 10; i++) { PostMessage(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0); Sleep(50); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) { g_AllowInterruption = TRUE; return 0; } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); hThread=0; g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT unsigned int ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT unsigned int ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { g_script.Destroy(); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { g_script.Destroy(); g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_LibCOMServer, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/unsigned int* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/unsigned int* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } -HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/unsigned int* aLabelPointer) +HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/__int64* aLabelPointer) { if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false) ; return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ unsigned int* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(Variant2T(aLabelName,buf),Variant2I(nowait)); return S_OK; } -HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ unsigned int* pFunc) +HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ __int64* pFunc) { if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::ahkKey(/*[in]*/ VARIANT name,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkKey(Variant2T(name,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(Variant2T(filepath,buf),Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; // if (0 && GetModuleFileName(g_hInstance, buf, MAX_PATH)) // for debugging com if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_LibCOMServer) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_LibCOMServer) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; } // // Server unregistration // STDAPI DllUnregisterServer() { HRESULT hr = UnregisterServer(CLSID_CoCOMServerOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_LibCOMServer) ; hr = UnregisterServer(CLSID_CoCOMServer, g_szVerIndProgID, g_szProgID, LIBID_LibCOMServer) ; if (SUCCEEDED(hr)) { UnRegisterTypeLib( g_hInstance, NULL); } return hr; } #endif #endif \ No newline at end of file diff --git a/source/exports.cpp b/source/exports.cpp index f54501c..a93c745 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,594 +1,593 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} -unsigned int com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} +__int64 com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} unsigned int com_ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} -unsigned int com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} +__int64 com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC unsigned int com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL unsigned int com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} unsigned int com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } -EXPORT unsigned int ahkFindFunc(LPTSTR funcname) +EXPORT __int64 ahkFindFunc(LPTSTR funcname) { - return (unsigned int)g_script.FindFunc(funcname); + return (__int64)g_script.FindFunc(funcname); } -EXPORT unsigned int ahkFindLabel(LPTSTR aLabelName) +EXPORT __int64 ahkFindLabel(LPTSTR aLabelName) { - Label *aLabel = g_script.FindLabel(aLabelName) ; - return (unsigned int)aLabel->mJumpToLine; + return (__int64)g_script.FindLabel(aLabelName); } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT unsigned int ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (unsigned int)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (unsigned int) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC // Finalize addFile/addScript/ahkExec BOOL FinalizeScript(Line *aFirstLine,int aFuncCount,int aHotkeyCount) { #ifndef MINIDLL if (Hotkey::sHotkeyCount>aHotkeyCount) { Line::ToggleSuspendState(); Line::ToggleSuspendState(); } #endif if (!(g_script.AddLine(ACT_RETURN) && g_script.AddLine(ACT_RETURN))) // Second return guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; // Check for any unprocessed static initializers: if (g_script.mFirstStaticLine) { if (!g_script.PreparseBlocks(g_script.mFirstStaticLine)) return LOADING_FAILED; // Prepend all Static initializers to the end of script. g_script.mLastLine->mNextLine = g_script.mFirstStaticLine; g_script.mLastLine = g_script.mLastStaticLine; if (!g_script.AddLine(ACT_RETURN)) return LOADING_FAILED; } if (g_Warn_LocalSameAsGlobal) { // Scan all "automatic" local vars and warn the user if there are any with the same // name as a global variable, since that would probably indicate a missing declaration: int i, j; Func *func; for (i = aFuncCount; i < g_script.mFuncCount; ++i) { if (!(func = g_script.mFunc[i])->mIsBuiltIn) { for (j = 0; j < func->mVarCount; ++j) g_script.MaybeWarnLocalSameAsGlobal(func, func->mVar[j]); for (j = 0; j < func->mLazyVarCount; ++j) g_script.MaybeWarnLocalSameAsGlobal(func, func->mLazyVar[j]); } } } if (!g_script.PreparseIfElse(aFirstLine)) return LOADING_FAILED; if (g_script.mFirstStaticLine) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstStaticLine, (LPARAM)NULL); return 0; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aIgnoreLoadFailure > 1) { if (aIgnoreLoadFailure > 2) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; } // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #else int HotkeyCount = NULL; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; int aFuncCount = g_script.mFuncCount; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,HotkeyCount)) return LOADING_FAILED; if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; // FirstStaticLine is used only once and therefor can be reused g_script.mFirstStaticLine = NULL; g_script.mLastStaticLine = NULL; int aFuncCount = g_script.mFuncCount; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (FinalizeScript(oldLastLine->mNextLine,aFuncCount,UINT_MAX)) return LOADING_FAILED; SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)NULL); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } SimpleHeap::Delete(Line::sSourceFile[Line::sSourceFileCount]); --Line::sSourceFileCount; oldLastLine->mNextLine = NULL; return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: diff --git a/source/exports.h b/source/exports.h index 7f57a62..59dc2a0 100644 --- a/source/exports.h +++ b/source/exports.h @@ -1,75 +1,76 @@ // Naveen v1. #define EXPORT __declspec(dllexport) #ifndef exports_h #define exports_h #define EXPORT extern "C" __declspec(dllexport) #define BIF(fun) void fun(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) EXPORT BOOL ahkPause(LPTSTR aChangeTo); -EXPORT unsigned int ahkFindLabel(LPTSTR aLabelName); +EXPORT __int64 ahkFindLabel(LPTSTR aLabelName); EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar); EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value); EXPORT unsigned int ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait); EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait = 0); -EXPORT unsigned int ahkFindFunc(LPTSTR funcname) ; +EXPORT __int64 ahkFindFunc(LPTSTR funcname) ; EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1 = _T(""), LPTSTR param2 = _T(""), LPTSTR param3 = _T(""), LPTSTR param4 = _T(""), LPTSTR param5 = _T(""), LPTSTR param6 = _T(""), LPTSTR param7 = _T(""), LPTSTR param8 = _T(""), LPTSTR param9 = _T(""), LPTSTR param10 = _T("")); EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1 = _T(""), LPTSTR param2 = _T(""), LPTSTR param3 = _T(""), LPTSTR param4 = _T(""), LPTSTR param5 = _T(""), LPTSTR param6 = _T(""), LPTSTR param7 = _T(""), LPTSTR param8 = _T(""), LPTSTR param9 = _T(""), LPTSTR param10 = _T("")); EXPORT BOOL ahkKey(LPTSTR keys); #ifndef AUTOHOTKEYSC EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude = false, int aIgnoreLoadFailure = 0); EXPORT unsigned int addScript(LPTSTR script, int aReplace = 0); EXPORT BOOL ahkExec(LPTSTR script); #endif void callFuncDllVariant(FuncAndToken *aFuncAndToken); void callFuncDll(FuncAndToken *aFuncAndToken); BIF(BIF_FindFunc); +BIF(BIF_FindLabel); BIF(BIF_Getvar); BIF(BIF_Static) ; BIF(BIF_Alias) ; BIF(BIF_CacheEnable) ; BIF(BIF_getTokenValue) ; int initPlugins(); #ifdef _USRDLL EXPORT unsigned int ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); EXPORT unsigned int ahktextdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); EXPORT BOOL ahkTerminate(bool kill=0); EXPORT BOOL com_ahkTerminate(bool kill); EXPORT BOOL ahkReady(); EXPORT BOOL com_ahkReady(); EXPORT BOOL ahkReload(); EXPORT BOOL com_ahkReload(); void reloadDll(); ResultType terminateDll(); #endif #endif #ifndef MINIDLL //COM virtual functions declaration BOOL com_ahkPause(LPTSTR aChangeTo); -unsigned int com_ahkFindLabel(LPTSTR aLabelName); +__int64 com_ahkFindLabel(LPTSTR aLabelName); // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar); // unsigned int com_ahkassign(LPTSTR name, LPTSTR value); unsigned int com_ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait); BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait); -unsigned int com_ahkFindFunc(LPTSTR funcname); +__int64 com_ahkFindFunc(LPTSTR funcname); // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10); unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10); BOOL com_ahkKey(LPTSTR keys); #ifndef AUTOHOTKEYSC unsigned int com_addScript(LPTSTR script, int aExecute); BOOL com_ahkExec(LPTSTR script); unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure); #endif #ifdef _USRDLL unsigned int com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); unsigned int com_ahktextdll(LPTSTR fileName,LPTSTR argv,LPTSTR args); BOOL com_ahkTerminate(bool kill); BOOL com_ahkReady(); BOOL com_ahkReload(); #endif #endif \ No newline at end of file diff --git a/source/lowlevelbif.cpp b/source/lowlevelbif.cpp index 97c3f14..33e4593 100644 --- a/source/lowlevelbif.cpp +++ b/source/lowlevelbif.cpp @@ -1,113 +1,126 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" #define BIF(fun) void fun(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) BIF(BIF_FindFunc) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = _T(""); // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. TCHAR funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. LPTSTR funcname = TokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } +BIF(BIF_FindLabel) // HotKeyIt Added in 1.1.02.00 +{ + // Set default return value in case of early return. + aResultToken.symbol = SYM_INTEGER ; + aResultToken.marker = _T(""); + // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. + TCHAR labelname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. + LPTSTR labelname = TokenToString(*aParam[0], labelname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). + int labelname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], labelname); + aResultToken.value_int64 = (__int64)ahkFindLabel(labelname); + return; +} + BIF(BIF_Getvar) { int i = 0; if (aParam[0]->symbol == SYM_VAR) i = (int)aParam[0]->var; aResultToken.value_int64 = i; } BIF(BIF_Static) { if (aParam[0]->symbol == SYM_VAR) { Var *var = aParam[0]->var; if (var->mType == VAR_ALIAS) var = var->mAliasFor; var->mAttrib |= VAR_LOCAL_STATIC; } } BIF(BIF_Alias) { ExprTokenType &aParam0 = *aParam[0]; ExprTokenType &aParam1 = *aParam[1]; if (aParam0.symbol == SYM_VAR) { Var &var = *aParam0.var; UINT len = 0; switch (aParam1.symbol) { case SYM_VAR: case SYM_INTEGER: len = (UINT)aParam1.var; break; // HotKeyIt H10 added to accept dynamic text and also when value is returned by ahkgetvar in AutoHotkey.dll case SYM_OPERAND: len = (UINT)ATOI64(aParam1.marker); } var.mType = len ? VAR_ALIAS : VAR_NORMAL; var.mByteLength = len; } } BIF(BIF_CacheEnable) { if (aParam[0]->symbol == SYM_VAR) { (aParam[0]->var->mType == VAR_ALIAS ? aParam[0]->var->mAliasFor : aParam[0]->var) ->mAttrib &= ~VAR_ATTRIB_CACHE_DISABLED; } } BIF(BIF_getTokenValue) { ExprTokenType *token = aParam[0]; if (token->symbol != SYM_INTEGER) return; token = (ExprTokenType*) token->value_int64; if (token->symbol == SYM_VAR) { Var &var = *token->var; VarAttribType cache_attrib = var.mAttrib & (VAR_ATTRIB_HAS_VALID_INT64 | VAR_ATTRIB_HAS_VALID_DOUBLE); if (cache_attrib) { aResultToken.symbol = (SymbolType) (cache_attrib >> 4); aResultToken.value_int64 = var.mContentsInt64; } else if (var.mAttrib & VAR_ATTRIB_OBJECT) { aResultToken.symbol = SYM_OBJECT; aResultToken.object = var.mObject; } else { aResultToken.symbol = SYM_OPERAND; aResultToken.marker = var.mCharContents; } } else { aResultToken.symbol = token->symbol; aResultToken.value_int64 = token->value_int64; } if (aResultToken.symbol == SYM_OBJECT) aResultToken.object->AddRef(); } \ No newline at end of file
tinku99/ahkdll
5eb22ef35e24764287a118492d983ca220a54914
Another fix in addScript and addFile toggle Hotkey + Hotstrings
diff --git a/source/exports.cpp b/source/exports.cpp index 7a90822..13dd8cf 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,780 +1,792 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} unsigned int com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} unsigned int com_ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} unsigned int com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC unsigned int com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL unsigned int com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} unsigned int com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT unsigned int ahkFindFunc(LPTSTR funcname) { return (unsigned int)g_script.FindFunc(funcname); } EXPORT unsigned int ahkFindLabel(LPTSTR aLabelName) { Label *aLabel = g_script.FindLabel(aLabelName) ; return (unsigned int)aLabel->mJumpToLine; } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT unsigned int ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (unsigned int)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (unsigned int) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC #ifdef _USRDLL // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. static int filesAdded = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #endif Line *oldLastLine = g_script.mLastLine; if (aIgnoreLoadFailure > 1) // if third param is > 1, reset all functions, labels, remove hotkeys { g_script.mFuncCount = 0; g_script.mFirstLabel = NULL ; g_script.mLastLabel = NULL ; g_script.mLastFunc = NULL ; g_script.mFirstLine = NULL ; g_script.mLastLine = NULL ; g_script.mCurrLine = NULL ; if (filesAdded == 0) { SimpleHeap::sBlockCount = 0 ; SimpleHeap::sFirst = NULL; SimpleHeap::sLast = NULL; SimpleHeap::sMostRecentlyAllocated = NULL; } if (filesAdded > 0) { // Naveen v9 free simpleheap memory for late include files SimpleHeap *next, *curr; for (curr = SimpleHeap::sFirst; curr != NULL;) { next = curr->mNextBlock; // Save this member's value prior to deleting the object. curr->~SimpleHeap() ; curr = next; } SimpleHeap::sBlockCount = 0 ; SimpleHeap::sFirst = NULL; SimpleHeap::sLast = NULL; SimpleHeap::sMostRecentlyAllocated = NULL; /* Naveen: the following is causing a memory leak in the exe version of clearing the simple heap v10 g_script.mVar = NULL ; g_script.mVarCount = 0 ; g_script.mVarCountMax = 0 ; g_script.mLazyVar = NULL ; g_script.mLazyVarCount = 0 ; */ } g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; #ifndef MINIDLL if (Hotkey::sHotkeyCount>HotkeyCount) - Line::ToggleSuspendState();Line::ToggleSuspendState(); + { + Line::ToggleSuspendState(); + Line::ToggleSuspendState(); + } #endif PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)g_script.mFirstLine); filesAdded += 1; return (unsigned int) g_script.mFirstLine; } else { g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; #ifndef MINIDLL if (Hotkey::sHotkeyCount>HotkeyCount) - Line::ToggleSuspendState();Line::ToggleSuspendState(); + { + Line::ToggleSuspendState(); + Line::ToggleSuspendState(); + } #endif return (unsigned int) oldLastLine->mNextLine; // } return 0; // never reached } #else // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if (aIgnoreLoadFailure > 1) // if third param is > 1, reset all functions, labels, remove hotkeys { g_script.mFuncCount = 0; g_script.mFirstLabel = NULL ; g_script.mLastLabel = NULL ; g_script.mLastFunc = NULL ; g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, aIgnoreLoadFailure); } else { g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; #ifndef MINIDLL if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; #endif if (Hotkey::sHotkeyCount>HotkeyCount) - Line::ToggleSuspendState();Line::ToggleSuspendState(); + { + Line::ToggleSuspendState(); + Line::ToggleSuspendState(); + } return (unsigned int) oldLastLine->mNextLine; // } #endif // _USRDLL #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; #ifndef MINIDLL int HotkeyCount = Hotkey::sHotkeyCount; #endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; return LOADING_FAILED; } #ifndef MINIDLL if (Hotkey::sHotkeyCount>HotkeyCount) - Line::ToggleSuspendState();Line::ToggleSuspendState(); + { + Line::ToggleSuspendState(); + Line::ToggleSuspendState(); + } #endif if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; // } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (!oldLastLine->mNextLine) //H30 - if no line was added, return return OK; g_script.PreparseIfElse(oldLastLine->mNextLine); SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } oldLastLine->mNextLine = NULL; // return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. AssignVariant(*aFunc->mParam[1].var, param2, false); if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 { AssignVariant(*aFunc->mParam[2].var, param3, false); if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 { AssignVariant(*aFunc->mParam[3].var, param4, false); if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 { AssignVariant(*aFunc->mParam[4].var, param5, false); if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 { AssignVariant(*aFunc->mParam[5].var, param6, false); if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 { AssignVariant(*aFunc->mParam[6].var, param7, false); if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 { AssignVariant(*aFunc->mParam[7].var, param8, false); if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 { AssignVariant(*aFunc->mParam[8].var, param9, false); if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 { AssignVariant(*aFunc->mParam[9].var, param10, false); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; }
tinku99/ahkdll
3431c80330b75be50497b2398665ebe4a2c92565
Fixed ExitApp for dll and addScript and addFile Hotkey + Hotstrings
diff --git a/source/dllmain.cpp b/source/dllmain.cpp index 5450d9f..31cbc05 100644 --- a/source/dllmain.cpp +++ b/source/dllmain.cpp @@ -1,1055 +1,1057 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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 #ifdef _USRDLL #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "window.h" // For MsgBox() & SetForegroundLockTimeout() #include "TextIO.h" #include "windows.h" // N11 #include "exports.h" // N11 #include <process.h> // N11 #include <objbase.h> // COM #include "ComServer_i.h" #include "ComServer_i.c" #include <atlbase.h> // CComBSTR #include "Registry.h" #include "ComServerImpl.h" #include "MemoryModule.h" //#include <string> // General note: // The use of Sleep() should be avoided *anywhere* in the code. Instead, call MsgSleep(). // The reason for this is that if the keyboard or mouse hook is installed, a straight call // to Sleep() will cause user keystrokes & mouse events to lag because the message pump // (GetMessage() or PeekMessage()) is the only means by which events are ever sent to the // hook functions. static LPTSTR scriptstring; // Naveen v1. HANDLE hThread // Todo: move this to struct nameHinstance static HANDLE hThread; static struct nameHinstance { HINSTANCE hInstanceP; LPTSTR name ; LPTSTR argv; LPTSTR args; // TCHAR argv[1000]; // TCHAR args[1000]; int istext; } nameHinstanceP ; // Naveen v1. hThread2 and threadCount // Todo: remove these as multithreading was implemented // with multiple loading of the dll under separate names. static int threadCount = 1 ; static HANDLE hThread2; unsigned __stdcall runScript( void* pArguments ); // Naveen v1. DllMain() - puts hInstance into struct nameHinstanceP // so it can be passed to OldWinMain() // hInstance is required for script initialization // probably for window creation // Todo: better cleanup in DLL_PROCESS_DETACH: windows, variables, no exit from script BOOL APIENTRY DllMain(HMODULE hInstance,DWORD fwdReason, LPVOID lpvReserved) { switch(fwdReason) { case DLL_PROCESS_ATTACH: { nameHinstanceP.hInstanceP = (HINSTANCE)hInstance; g_hInstance = (HINSTANCE)hInstance; #ifdef AUTODLL ahkdll("autoload.ahk", "", ""); // used for remoteinjection of dll #endif break; } case DLL_THREAD_ATTACH: { break; } case DLL_PROCESS_DETACH: { int lpExitCode = 0; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if ( lpExitCode == 259 ) CloseHandle( hThread ); // need better cleanup: windows, variables, no exit from script break; } case DLL_THREAD_DETACH: break; } return(TRUE); // a FALSE will abort the DLL attach } int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // Init any globals not in "struct g" that need it: g_MainThreadID = GetCurrentThreadId(); InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x). if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround. *g_WorkingDir = '\0'; // Unlike the below, the above must not be Malloc'd because the contents can later change to something // as large as MAX_PATH by means of the SetWorkingDir command. g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command. // Set defaults, to be overridden by command line args we receive: bool restart_mode = false; #ifndef AUTOHOTKEYSC LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL; #endif // The problem of some command line parameters such as /r being "reserved" is a design flaw (one that // can't be fixed without breaking existing scripts). Fortunately, I think it affects only compiled // scripts because running a script via AutoHotkey.exe should avoid treating anything after the // filename as switches. This flaw probably occurred because when this part of the program was designed, // there was no plan to have compiled scripts. // // Examine command line args. Rules: // Any special flags (e.g. /force and /restart) must appear prior to the script filespec. // The script filespec (if present) must be the first non-backslash arg. // All args that appear after the filespec are considered to be parameters for the script // and will be added as variables %1% %2% etc. // The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters // unless the filename is explicitly given (shouldn't be an issue for 99.9% of people). TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%). Var *var; bool switch_processing_is_complete = false; int script_param_num = 1; LPTSTR args[4]; //args[0] = __targv[0]; // name of host program args[0] = GetCommandLine(); args[1] = nameHinstanceP.argv; // 1 option such as /Debug /R /F /STDOUT args[2] = nameHinstanceP.name; // name of script to launch args[3] = nameHinstanceP.args; // script parameters, all in one string (* char) int argc = 4; for (int i = 1; i < argc; ++i) // Naveen changed from: for (int i = 1; i < __argc; ++i) see above { // Naveen: v6.1 put options in script variables as well param = args[i]; // Naveen changed from: __argv[i]; see above if ( !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(param); ++script_param_num; } // Naveen: v6.1 only argv needs special processing // script will do its own parameter parsing param = nameHinstanceP.argv ; // #ifdef CONFIG_DEBUGGER g_DebuggerHost = "localhost"; g_DebuggerPort = "9000"; #endif #ifndef AUTOHOTKEYSC if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag. { size_t filespec_length = _tcslen(script_filespec); if (filespec_length >= CONVERSION_FLAG_LENGTH) { LPTSTR cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH; // Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one). if (!_tcsicmp(cp, CONVERSION_FLAG)) return Line::ConvertEscapeChar(script_filespec); } } #endif // Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero: if ( !(var = g_script.FindOrAddVar(_T("0"))) ) return CRITICAL_ERROR; // Realistically should never happen. var->Assign(script_param_num - 1); // N11 Var *A_ScriptParams; A_ScriptParams = g_script.FindOrAddVar(_T("A_ScriptParams")); A_ScriptParams->Assign(nameHinstanceP.args); Var *A_ScriptOptions; A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions")); A_ScriptOptions->Assign(nameHinstanceP.argv); global_init(*g); // Set defaults prior to the below, since below might override them for AutoIt2 scripts. // Set up the basics of the script: if (g_script.Init(*g, script_filespec, restart_mode,hInstance,(bool)nameHinstanceP.istext) != OK) // Set up the basics of the script, using the above. return CRITICAL_ERROR; // Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below, // never returns, perhaps because it contains an infinite loop (intentional or not): CopyMemory(&g_default, g, sizeof(global_struct)); //if (nameHinstanceP.istext) // GetCurrentDirectory(MAX_PATH, g_script.mFileDir); // Could use CreateMutex() but that seems pointless because we have to discover the // hWnd of the existing process so that we can close or restart it, so we would have // to do this check anyway, which serves both purposes. Alt method is this: // Even if a 2nd instance is run with the /force switch and then a 3rd instance // is run without it, that 3rd instance should still be blocked because the // second created a 2nd handle to the mutex that won't be closed until the 2nd // instance terminates, so it should work ok: //CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness. //if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS) #ifdef AUTOHOTKEYSC LineNumberType load_result = g_script.LoadFromFile(); #else //HotKeyIt changed to load from Text in dll as well when file does not exist LineNumberType load_result = !nameHinstanceP.istext ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec); #endif if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call). return CRITICAL_ERROR; // Should return this value because PostQuitMessage() also uses it. if (!load_result) // LoadFromFile() relies upon us to do this check. No lines were loaded, so we're done. return 0; // Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of // SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts // and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16: #ifndef _USRDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #else #ifndef MINIDLL if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE) g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT; #endif #endif #ifndef MINIDLL /* HWND w_existing = NULL; UserMessages reason_to_close_prior = (UserMessages)0; if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch) { // Note: the title below must be constructed the same was as is done by our // CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle: if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) { if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE) return 0; if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE) if (MsgBox(_T("An older instance of this script is already running. Replace it with this") _T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.") , MB_YESNO, g_script.mFileName) == IDNO) return 0; // Otherwise: reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE; } } if (!reason_to_close_prior && restart_mode) if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle)) reason_to_close_prior = AHK_EXIT_BY_RELOAD; if (reason_to_close_prior) { // Now that the script has been validated and is ready to run, close the prior instance. // We wait until now to do this so that the prior instance's "restart" hotkey will still // be available to use again after the user has fixed the script. UPDATE: We now inform // the prior instance of why it is being asked to close so that it can make that reason // available to the OnExit subroutine via a built-in variable: terminateDll(); //PostMessage(w_existing, WM_CLOSE, 0, 0); // Wait for it to close before we continue, so that it will deinstall any // hooks and unregister any hotkeys it has: int interval_count; for (interval_count = 0; ; ++interval_count) { Sleep(10); // No need to use MsgSleep() in this case. if (!IsWindow(w_existing)) break; // done waiting. if (interval_count == 100) { // This can happen if the previous instance has an OnExit subroutine that takes a long // time to finish, or if it's waiting for a network drive to timeout or some other // operation in which it's thread is occupied. if (MsgBox(_T("Could not close the previous instance of this script. Keep waiting?"), 4) == IDNO) return CRITICAL_ERROR; interval_count = 0; } } // Give it a small amount of additional time to completely terminate, even though // its main window has already been destroyed: Sleep(100); } // Call this only after closing any existing instance of the program, // because otherwise the change to the "focus stealing" setting would never be undone: SetForegroundLockTimeout(); */ #endif // Create all our windows and the tray icon. This is done after all other chances // to return early due to an error have passed, above. if (g_script.CreateWindows() != OK) return CRITICAL_ERROR; // At this point, it is nearly certain that the script will be executed. // v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately // rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little // impact on performance given the OS's built-in caching. I looked at the source code for setvbuf() // and it seems like it should execute very quickly. Code size seems to be about 75 bytes. setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout. #ifndef MINIDLL if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem)))) ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed. //else leave it NULL as it was initialized in globaldata. #endif // MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required." // Therefore, in case it's a high overhead call, it's not done on XP or later: if (!g_os.IsWinXPorLater()) { // Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal // controls, InitCommonControlsEx() must be called. But since Ex() requires comctl32.dll // 4.70+, must get the function's address dynamically in case the program is running on // Windows 95/NT without the updated DLL (otherwise the program would not launch at all). typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX); MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType) GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler. if (MyInitCommonControlsEx) { INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls(). MyInitCommonControlsEx(&icce); } else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4. InitCommonControls(); } // Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the // top part (the auto-execute part) of the script so that they will be in effect even if the // top part is something that's very involved and requires user interaction: #ifndef MINIDLL Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop) //Hotkey::InstallKeybdHook(); //Hotkey::InstallMouseHook(); //if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0) // AddRemoveHooks(3); #endif g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp. Sleep(20); //free(nameHinstanceP.name); Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable. if (clipboard_var) // This is done here rather than upon variable creation speed up runtime/dynamic variable creation. // Since the clipboard can be changed by activity outside the program, don't read-cache its contents. // Since other applications and the user should see any changes the program makes to the clipboard, // don't write-cache it either. clipboard_var->DisableCache(); // Run the auto-execute part at the top of the script (this call might never return): if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort. return CRITICAL_ERROR; // REMEMBER: The call above will never return if one of the following happens: // 1) The AutoExec section never finishes (e.g. infinite loop). // 2) The AutoExec function uses uses the Exit or ExitApp command to terminate the script. // 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit). // Call it in this special mode to kick off the main event loop. // Be sure to pass something >0 for the first param or it will // return (and we never want this to return): MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES); return 0; // Never executed; avoids compiler warning. } // Naveen: v1. runscript() - runs the script in a separate thread compared to host application. unsigned __stdcall runScript( void* pArguments ) { struct nameHinstance a = *(struct nameHinstance *)pArguments; OleInitialize(NULL); HINSTANCE hInstance = a.hInstanceP; LPTSTR fileName = a.name; OldWinMain(hInstance, 0, fileName, 0); _endthreadex( (DWORD)EARLY_RETURN ); return 0; } EXPORT BOOL ahkTerminate(bool kill) { int lpExitCode = 0; + g_AllowInterruption = FALSE; GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); if (!kill) for (int i = 0; g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259) && i < 10; i++) { PostMessage(g_hWnd, AHK_EXIT_BY_SINGLEINSTANCE, EARLY_EXIT, 0); Sleep(50); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } if (lpExitCode != 0 && lpExitCode != 259) + { + g_AllowInterruption = TRUE; return 0; - Line::sSourceFileCount = 0; - global_clear_state(*g); + } g_script.Destroy(); TerminateThread(hThread, (DWORD)EARLY_EXIT); CloseHandle(hThread); - g_script.mIsReadyToExecute = false; + hThread=0; + g_AllowInterruption = TRUE; return 0; } void WaitIsReadyToExecute() { int lpExitCode = 0; while (!g_script.mIsReadyToExecute && (lpExitCode == 0 || lpExitCode == 259)) { Sleep(10); GetExitCodeThread(hThread,(LPDWORD)&lpExitCode); } } unsigned runThread() { if (hThread) ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); //hThread = (HANDLE)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&runScript,&nameHinstanceP,0,(LPDWORD)&threadID); //hThread = AfxBeginThread(&runScript,&nameHinstanceP,THREAD_PRIORITY_NORMAL,0,0,NULL); WaitIsReadyToExecute(); return (unsigned int)hThread; } int setscriptstrings(LPTSTR fileName, LPTSTR argv, LPTSTR args) { LPTSTR newstring = (LPTSTR)realloc(scriptstring,(_tcslen(fileName)+_tcslen(argv)+_tcslen(args)+3)*sizeof(TCHAR)); if (!newstring) return 1; scriptstring = newstring; _tcscpy(scriptstring,fileName); _tcscpy(scriptstring + _tcslen(fileName) + 1,argv); _tcscpy(scriptstring + _tcslen(fileName) + _tcslen(argv) + 2,args); nameHinstanceP.name = scriptstring; nameHinstanceP.argv = scriptstring + _tcslen(fileName) + 1 ; nameHinstanceP.args = scriptstring + _tcslen(fileName) + _tcslen(argv) + 2 ; return 0; } EXPORT unsigned int ahkdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = *fileName ? 0 : 1; return runThread(); } // HotKeyIt ahktextdll EXPORT unsigned int ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args) { if (setscriptstrings(*fileName ? fileName : _T("#Persistent\n#NoTrayIcon"), argv, args)) return 0; nameHinstanceP.istext = 1; return runThread(); } void reloadDll() { - unsigned threadID; - Line::sSourceFileCount = 0; g_script.Destroy(); - hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, &threadID ); - _endthreadex( (DWORD)EARLY_RETURN ); + hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); + g_AllowInterruption = TRUE; + _endthreadex( (DWORD)EARLY_RETURN ); } ResultType terminateDll() { - Line::sSourceFileCount = 0; g_script.Destroy(); + g_AllowInterruption = TRUE; _endthreadex( (DWORD)EARLY_EXIT ); return EARLY_EXIT; } EXPORT BOOL ahkReload() { ahkTerminate(0); hThread = (HANDLE)_beginthreadex( NULL, 0, &runScript, &nameHinstanceP, 0, 0 ); return 0; } EXPORT BOOL ahkReady() // HotKeyIt check if dll is ready to execute { return g_script.mIsReadyToExecute; } #ifndef MINIDLL // COM Implementation // static long g_cComponents = 0 ; // Count of active components static long g_cServerLocks = 0 ; // Count of locks // Friendly name of component const char g_szFriendlyName[] = "AutoHotkey Script" ; // Version-independent ProgID const char g_szVerIndProgID[] = "AutoHotkey.Script" ; // ProgID const char g_szProgID[] = "AutoHotkey.Script.1" ; #ifdef _WIN64 const char g_szFriendlyNameOptional[] = "AutoHotkey Script X64" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.X64" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.X64.1" ; #else #ifdef _UNICODE const char g_szFriendlyNameOptional[] = "AutoHotkey Script UNICODE" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.UNICODE" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.UNICODE.1" ; #else const char g_szFriendlyNameOptional[] = "AutoHotkey Script ANSI" ; const char g_szVerIndProgIDOptional[] = "AutoHotkey.Script.ANSI" ; const char g_szProgIDOptional[] = "AutoHotkey.Script.ANSI.1" ; #endif // UNICODE #endif // WIN64 // // Constructor // CoCOMServer::CoCOMServer() : m_cRef(1) { InterlockedIncrement(&g_cComponents) ; m_ptinfo = NULL; LoadTypeInfo(&m_ptinfo, LIBID_LibCOMServer, IID_ICOMServer, 0); } // // Destructor // CoCOMServer::~CoCOMServer() { InterlockedDecrement(&g_cComponents) ; } // // IUnknown implementation // HRESULT __stdcall CoCOMServer::QueryInterface(const IID& iid, void** ppv) { if (iid == IID_IUnknown || iid == IID_ICOMServer || iid == IID_IDispatch) { *ppv = static_cast<ICOMServer*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CoCOMServer::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CoCOMServer::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // ICOMServer implementation // LPTSTR Variant2T(VARIANT var,LPTSTR buf) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return _T(""); else if (var.vt==VT_BSTR) return OLE2T(var.bstrVal); else if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) #ifdef _WIN64 return _ui64tot(var.uintVal,buf,10); #else return _ultot(var.uintVal,buf,10); #endif return _T(""); } unsigned int Variant2I(VARIANT var) { USES_CONVERSION; if (var.vt == VT_BYREF+VT_VARIANT) var = *var.pvarVal; if (var.vt == VT_ERROR) return 0; else if (var.vt == VT_BSTR) return ATOI(OLE2T(var.bstrVal)); else //if (var.vt==VT_I2 || var.vt==VT_I4 || var.vt==VT_I8) return var.uintVal; } HRESULT __stdcall CoCOMServer::ahktextdll(/*in,optional*/VARIANT script,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/unsigned int* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahktextdll(script.vt == VT_BSTR ? OLE2T(script.bstrVal) : Variant2T(script,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkdll(/*in,optional*/VARIANT filepath,/*in,optional*/VARIANT options,/*in,optional*/VARIANT params,/*out*/unsigned int* hThread) { USES_CONVERSION; TCHAR buf1[MAX_INTEGER_SIZE],buf2[MAX_INTEGER_SIZE],buf3[MAX_INTEGER_SIZE]; if (hThread==NULL) return ERROR_INVALID_PARAMETER; *hThread = com_ahkdll(filepath.vt == VT_BSTR ? OLE2T(filepath.bstrVal) : Variant2T(filepath,buf1) ,options.vt == VT_BSTR ? OLE2T(options.bstrVal) : Variant2T(options,buf2) ,params.vt == VT_BSTR ? OLE2T(params.bstrVal) : Variant2T(params,buf3)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkPause(/*in,optional*/VARIANT aChangeTo,/*out*/BOOL* paused) { if (paused==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *paused = com_ahkPause(Variant2T(aChangeTo,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkReady(/*out*/BOOL* ready) { if (ready==NULL) return ERROR_INVALID_PARAMETER; *ready = com_ahkReady(); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindLabel(/*in*/VARIANT aLabelName,/*out*/unsigned int* aLabelPointer) { if (aLabelPointer==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *aLabelPointer = com_ahkFindLabel(Variant2T(aLabelName,buf)); return S_OK; } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); HRESULT __stdcall CoCOMServer::ahkgetvar(/*in*/VARIANT name,/*[in,optional]*/ VARIANT getVar,/*out*/VARIANT *result) { if (result==NULL) return ERROR_INVALID_PARAMETER; //USES_CONVERSION; TCHAR buf[MAX_INTEGER_SIZE]; Var *var; ExprTokenType aToken ; var = g_script.FindVar(Variant2T(name,buf)) ; var->TokenToContents(aToken) ; VariantInit(result); // CComVariant b ; VARIANT b ; TokenToVariant(aToken, b); return VariantCopy(result, &b) ; // return S_OK ; // return b.Detach(result); } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); HRESULT __stdcall CoCOMServer::ahkassign(/*in*/VARIANT name, /*in*/VARIANT value,/*out*/unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR namebuf[MAX_INTEGER_SIZE]; Var *var; if ( !(var = g_script.FindOrAddVar(Variant2T(name,namebuf))) ) return ERROR_INVALID_PARAMETER; // Realistically should never happen. AssignVariant(*var, value, false) ; return S_OK; } HRESULT __stdcall CoCOMServer::ahkExecuteLine(/*[in,optional]*/ VARIANT line,/*[in,optional]*/ VARIANT aMode,/*[in,optional]*/ VARIANT wait,/*[out, retval]*/ unsigned int* pLine) { if (pLine==NULL) return ERROR_INVALID_PARAMETER; *pLine = com_ahkExecuteLine(Variant2I(line),Variant2I(aMode),Variant2I(wait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkLabel(/*[in]*/ VARIANT aLabelName,/*[in,optional]*/ VARIANT nowait,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkLabel(Variant2T(aLabelName,buf),Variant2I(nowait)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkFindFunc(/*[in]*/ VARIANT FuncName,/*[out, retval]*/ unsigned int* pFunc) { if (pFunc==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *pFunc = com_ahkFindFunc(Variant2T(FuncName,buf)); return S_OK; } VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost); HRESULT __stdcall CoCOMServer::ahkFunction(/*[in]*/ VARIANT FuncName,/*[in,optional]*/ VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ VARIANT* returnVal) { if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 1); VariantInit(returnVal); return VariantCopy(returnVal, &b) ; // return b.Detach(returnVal); } HRESULT __stdcall CoCOMServer::ahkPostFunction(/*[in]*/ VARIANT FuncName,VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10,/*[out, retval]*/ unsigned int* returnVal) { if (returnVal==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE] ; // CComVariant b ; VARIANT b ; b = ahkFunctionVariant(Variant2T(FuncName,buf), param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, 0); return 0; } HRESULT __stdcall CoCOMServer::ahkKey(/*[in]*/ VARIANT name,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkKey(Variant2T(name,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::addScript(/*[in]*/ VARIANT script,/*[in,optional]*/ VARIANT replace,/*[out, retval]*/ unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addScript(Variant2T(script,buf),Variant2I(replace)); return S_OK; } HRESULT __stdcall CoCOMServer::addFile(/*[in]*/ VARIANT filepath,/*[in,optional]*/ VARIANT aAllowDuplicateInclude,/*[in,optional]*/ VARIANT aIgnoreLoadFailure,/*[out, retval]*/ unsigned int* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_addFile(Variant2T(filepath,buf),Variant2I(aAllowDuplicateInclude),Variant2I(aIgnoreLoadFailure)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkExec(/*[in]*/ VARIANT script,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; TCHAR buf[MAX_INTEGER_SIZE]; *success = com_ahkExec(Variant2T(script,buf)); return S_OK; } HRESULT __stdcall CoCOMServer::ahkTerminate(/*[in,optional]*/ VARIANT kill,/*[out, retval]*/ BOOL* success) { if (success==NULL) return ERROR_INVALID_PARAMETER; *success = com_ahkTerminate(Variant2I(kill)); return S_OK; } HRESULT CoCOMServer::LoadTypeInfo(ITypeInfo ** pptinfo, const CLSID &libid, const CLSID &iid, LCID lcid) { HRESULT hr; LPTYPELIB ptlib = NULL; LPTYPEINFO ptinfo = NULL; *pptinfo = NULL; // Load type library. hr = LoadRegTypeLib(libid, 1, 0, lcid, &ptlib); if (FAILED(hr)) return hr; // Get type information for interface of the object. hr = ptlib->GetTypeInfoOfGuid(iid, &ptinfo); if (FAILED(hr)) { ptlib->Release(); return hr; } ptlib->Release(); *pptinfo = ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 1; return S_OK; } HRESULT __stdcall CoCOMServer::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { *pptinfo = NULL; if(itinfo != 0) return ResultFromScode(DISP_E_BADINDEX); m_ptinfo->AddRef(); // AddRef and return pointer to cached // typeinfo for this object. *pptinfo = m_ptinfo; return NOERROR; } HRESULT __stdcall CoCOMServer::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(m_ptinfo, rgszNames, cNames, rgdispid); } HRESULT __stdcall CoCOMServer::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return DispInvoke( this, m_ptinfo, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // // Class factory IUnknown implementation // HRESULT __stdcall CFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast<IClassFactory*>(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast<IUnknown*>(*ppv)->AddRef() ; return S_OK ; } ULONG __stdcall CFactory::AddRef() { return InterlockedIncrement(&m_cRef) ; } ULONG __stdcall CFactory::Release() { if (InterlockedDecrement(&m_cRef) == 0) { delete this ; return 0 ; } return m_cRef ; } // // IClassFactory implementation // HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CoCOMServer* pA = new CoCOMServer ; if (pA == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pA->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. // (If QueryInterface failed, component will delete itself.) pA->Release() ; return hr ; } // LockServer HRESULT __stdcall CFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } /////////////////////////////////////////////////////////// // // Exported functions // // // Can DLL unload now? // STDAPI DllCanUnloadNow() { if ((g_cComponents == 0) && (g_cServerLocks == 0)) { return S_OK ; } else { return S_FALSE ; } } // // Get class factory // STDAPI DllGetClassObject(const CLSID& clsid, const IID& iid, void** ppv) { // Can we create this component? if (clsid != CLSID_CoCOMServer && clsid != CLSID_CoCOMServerOptional) { return CLASS_E_CLASSNOTAVAILABLE ; } TCHAR buf[MAX_PATH]; - if (0 && GetModuleFileName(g_hInstance, buf, MAX_PATH)) // for debugging com -// if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) +// if (0 && GetModuleFileName(g_hInstance, buf, MAX_PATH)) // for debugging com + if (GetModuleFileName(g_hInstance, buf, MAX_PATH)) { FILE *fp; unsigned char *data=NULL; size_t size; HMEMORYMODULE module; fp = _tfopen(buf, _T("rb")); if (fp == NULL) { return E_ACCESSDENIED; } fseek(fp, 0, SEEK_END); size = ftell(fp); data = (unsigned char *)_alloca(size); fseek(fp, 0, SEEK_SET); fread(data, 1, size, fp); fclose(fp); if (data) module = MemoryLoadLibrary(data); typedef HRESULT (__stdcall *pDllGetClassObject)(IN REFCLSID clsid,IN REFIID iid,OUT LPVOID FAR* ppv); pDllGetClassObject GetClassObject = (pDllGetClassObject)::MemoryGetProcAddress(module,"DllGetClassObject"); return GetClassObject(clsid,iid,ppv); } // Create class factory. CFactory* pFactory = new CFactory ; // Reference count set to 1 // in constructor if (pFactory == NULL) { return E_OUTOFMEMORY ; } // Get requested interface. HRESULT hr = pFactory->QueryInterface(iid, ppv) ; pFactory->Release() ; return hr ; } // // Server registration // STDAPI DllRegisterServer() { HRESULT hr = RegisterServer(g_hInstance, CLSID_CoCOMServerOptional, g_szFriendlyNameOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_LibCOMServer) ; hr= RegisterServer(g_hInstance, CLSID_CoCOMServer, g_szFriendlyName, g_szVerIndProgID, g_szProgID, LIBID_LibCOMServer) ; if (SUCCEEDED(hr)) { RegisterTypeLib( g_hInstance, NULL); } return hr; } // // Server unregistration // STDAPI DllUnregisterServer() { HRESULT hr = UnregisterServer(CLSID_CoCOMServerOptional, g_szVerIndProgIDOptional, g_szProgIDOptional, LIBID_LibCOMServer) ; hr = UnregisterServer(CLSID_CoCOMServer, g_szVerIndProgID, g_szProgID, LIBID_LibCOMServer) ; if (SUCCEEDED(hr)) { UnRegisterTypeLib( g_hInstance, NULL); } return hr; } #endif #endif \ No newline at end of file diff --git a/source/exports.cpp b/source/exports.cpp index a61a29e..7a90822 100644 --- a/source/exports.cpp +++ b/source/exports.cpp @@ -1,758 +1,780 @@ #include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" LPTSTR result_to_return_dll; //HotKeyIt H2 for ahkgetvar and ahkFunction return. // ExprTokenType aResultToken_to_return ; // for ahkPostFunction FuncAndToken aFuncAndTokenToReturn[10] ; // for ahkPostFunction int returnCount = 0 ; #ifdef _USRDLL #ifndef MINIDLL //COM virtual functions BOOL com_ahkPause(LPTSTR aChangeTo){return ahkPause(aChangeTo);} unsigned int com_ahkFindLabel(LPTSTR aLabelName){return ahkFindLabel(aLabelName);} // LPTSTR com_ahkgetvar(LPTSTR name,unsigned int getVar){return ahkgetvar(name,getVar);} // unsigned int com_ahkassign(LPTSTR name, LPTSTR value){return ahkassign(name,value);} unsigned int com_ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait){return ahkExecuteLine(line,aMode,wait);} BOOL com_ahkLabel(LPTSTR aLabelName, unsigned int nowait){return ahkLabel(aLabelName,nowait);} unsigned int com_ahkFindFunc(LPTSTR funcname){return ahkFindFunc(funcname);} // LPTSTR com_ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} // unsigned int com_ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10){return ahkPostFunction(func,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10);} BOOL com_ahkKey(LPTSTR keys){return ahkKey(keys);} #ifndef AUTOHOTKEYSC unsigned int com_addScript(LPTSTR script, int aExecute){return addScript(script,aExecute);} BOOL com_ahkExec(LPTSTR script){return ahkExec(script);} unsigned int com_addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure){return addFile(fileName,aAllowDuplicateInclude,aIgnoreLoadFailure);} #endif #ifdef _USRDLL unsigned int com_ahkdll(LPTSTR fileName,LPTSTR argv,LPTSTR args){return ahkdll(fileName,argv,args);} unsigned int com_ahktextdll(LPTSTR script,LPTSTR argv,LPTSTR args){return ahktextdll(script,argv,args);} BOOL com_ahkTerminate(bool kill){return ahkTerminate(kill);} BOOL com_ahkReady(){return ahkReady();} BOOL com_ahkReload(){return ahkReload();} #endif #endif #endif EXPORT BOOL ahkPause(LPTSTR aChangeTo) //Change pause state of a running script { if ( (((int)aChangeTo == 1 || (int)aChangeTo == 0) || (*aChangeTo == 'O' || *aChangeTo == 'o') && ( *(aChangeTo+1) == 'N' || *(aChangeTo+1) == 'n' ) ) || *aChangeTo == '1') { #ifndef MINIDLL Hotkey::ResetRunAgainAfterFinished(); #endif if ((int)aChangeTo == 0) { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } else { g->IsPaused = true; ++g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. } #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } else if (*aChangeTo != '\0') { g->IsPaused = false; --g_nPausedThreads; // For this purpose the idle thread is counted as a paused thread. #ifndef MINIDLL g_script.UpdateTrayIcon(); #endif } return (int)g->IsPaused; } EXPORT unsigned int ahkFindFunc(LPTSTR funcname) { return (unsigned int)g_script.FindFunc(funcname); } EXPORT unsigned int ahkFindLabel(LPTSTR aLabelName) { Label *aLabel = g_script.FindLabel(aLabelName) ; return (unsigned int)aLabel->mJumpToLine; } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } // Naveen: v1. ahkgetvar() EXPORT LPTSTR ahkgetvar(LPTSTR name,unsigned int getVar) { Var *ahkvar = g_script.FindOrAddVar(name); if (getVar != NULL) { if (ahkvar->mType == VAR_BUILTIN) return _T(""); result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,MAX_INTEGER_LENGTH); return ITOA64((int)ahkvar,result_to_return_dll); } if (!ahkvar->HasContents() && ahkvar->mType != VAR_BUILTIN ) return _T(""); if (*ahkvar->mCharContents == '\0') { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,(ahkvar->mByteCapacity ? ahkvar->mByteCapacity : ahkvar->mByteLength) + MAX_NUMBER_LENGTH + 1); if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit else if ( ahkvar->mType == VAR_ALIAS ) ITOA64(ahkvar->mAliasFor->mContentsInt64,result_to_return_dll); else if ( ahkvar->mType == VAR_NORMAL ) ITOA64(ahkvar->mContentsInt64,result_to_return_dll);//Hotkeyit } else { result_to_return_dll = (LPTSTR )realloc((LPTSTR )result_to_return_dll,ahkvar->mByteLength+1); if ( ahkvar->mType == VAR_ALIAS ) ahkvar->mAliasFor->Get(result_to_return_dll); //Hotkeyit removed ebiv.cpp and made ahkgetvar return all vars else if ( ahkvar->mType == VAR_NORMAL ) ahkvar->Get(result_to_return_dll); // var.getText() added in V1. else if ( ahkvar->mType == VAR_BUILTIN ) ahkvar->mBIV(result_to_return_dll,name); //Hotkeyit } return result_to_return_dll; } EXPORT unsigned int ahkassign(LPTSTR name, LPTSTR value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, _tcslen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } //HotKeyIt ahkExecuteLine() EXPORT unsigned int ahkExecuteLine(unsigned int line,unsigned int aMode,unsigned int wait) { Line *templine = (Line *)line; if (templine == NULL) return (unsigned int)g_script.mFirstLine; if (aMode) { if (wait) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)templine, (LPARAM)aMode); } if (templine = templine->mNextLine) if (templine->mActionType == ACT_BLOCK_BEGIN && templine->mAttribute) { for(;!(templine->mActionType == ACT_BLOCK_END && templine->mAttribute);) templine = templine->mNextLine; templine = templine->mNextLine; } return (unsigned int) templine; } EXPORT BOOL ahkLabel(LPTSTR aLabelName, unsigned int nowait) // 0 = wait = default { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { if (nowait) PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); else SendMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 1; } else return 0; } EXPORT unsigned int ahkPostFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return 0; } return -1; } EXPORT BOOL ahkKey(LPTSTR keys) { SendKeys(keys, false, SM_EVENT, 0, 1); // N11 sendahk return 0; } #ifndef AUTOHOTKEYSC #ifdef _USRDLL // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. static int filesAdded = 0 ; - +#ifndef MINIDLL + int HotkeyCount = Hotkey::sHotkeyCount; +#endif Line *oldLastLine = g_script.mLastLine; if (aIgnoreLoadFailure > 1) // if third param is > 1, reset all functions, labels, remove hotkeys { g_script.mFuncCount = 0; g_script.mFirstLabel = NULL ; g_script.mLastLabel = NULL ; g_script.mLastFunc = NULL ; g_script.mFirstLine = NULL ; g_script.mLastLine = NULL ; g_script.mCurrLine = NULL ; if (filesAdded == 0) { SimpleHeap::sBlockCount = 0 ; SimpleHeap::sFirst = NULL; SimpleHeap::sLast = NULL; SimpleHeap::sMostRecentlyAllocated = NULL; } if (filesAdded > 0) { // Naveen v9 free simpleheap memory for late include files SimpleHeap *next, *curr; for (curr = SimpleHeap::sFirst; curr != NULL;) { next = curr->mNextBlock; // Save this member's value prior to deleting the object. curr->~SimpleHeap() ; curr = next; } SimpleHeap::sBlockCount = 0 ; SimpleHeap::sFirst = NULL; SimpleHeap::sLast = NULL; SimpleHeap::sMostRecentlyAllocated = NULL; /* Naveen: the following is causing a memory leak in the exe version of clearing the simple heap v10 g_script.mVar = NULL ; g_script.mVarCount = 0 ; g_script.mVarCountMax = 0 ; g_script.mLazyVar = NULL ; g_script.mLazyVarCount = 0 ; */ } g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; +#ifndef MINIDLL + if (Hotkey::sHotkeyCount>HotkeyCount) + Line::ToggleSuspendState();Line::ToggleSuspendState(); +#endif PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)g_script.mFirstLine, (LPARAM)g_script.mFirstLine); filesAdded += 1; return (unsigned int) g_script.mFirstLine; } else { g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; +#ifndef MINIDLL + if (Hotkey::sHotkeyCount>HotkeyCount) + Line::ToggleSuspendState();Line::ToggleSuspendState(); +#endif return (unsigned int) oldLastLine->mNextLine; // } return 0; // never reached } #else // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(LPTSTR fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; +#ifndef MINIDLL + int HotkeyCount = Hotkey::sHotkeyCount; +#endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if (aIgnoreLoadFailure > 1) // if third param is > 1, reset all functions, labels, remove hotkeys { g_script.mFuncCount = 0; g_script.mFirstLabel = NULL ; g_script.mLastLabel = NULL ; g_script.mLastFunc = NULL ; g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, aIgnoreLoadFailure); } else { g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; - +#ifndef MINIDLL if (!g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) return LOADING_FAILED; +#endif + if (Hotkey::sHotkeyCount>HotkeyCount) + Line::ToggleSuspendState();Line::ToggleSuspendState(); return (unsigned int) oldLastLine->mNextLine; // } #endif // _USRDLL #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // HotKeyIt: addScript() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addScript(LPTSTR script, int aExecute) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; +#ifndef MINIDLL + int HotkeyCount = Hotkey::sHotkeyCount; +#endif if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine) || !g_script.PreparseIfElse(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc ; - return LOADING_FAILED; } +#ifndef MINIDLL + if (Hotkey::sHotkeyCount>HotkeyCount) + Line::ToggleSuspendState();Line::ToggleSuspendState(); +#endif if (aExecute > 0) { if (aExecute > 1) SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); else PostMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); } if (inFunc == 1 ) g->CurrentFunc = aFunc ; return (unsigned int) oldLastLine->mNextLine; // } #endif // AUTOHOTKEYSC #ifndef AUTOHOTKEYSC // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT BOOL ahkExec(LPTSTR script) { // dynamically include a script from text!! // labels, hotkeys, functions. Func * aFunc = NULL ; int inFunc = 0 ; if (g->CurrentFunc) // normally functions definitions are not allowed within functions. But we're in a function call, not a function definition right now. { aFunc = g->CurrentFunc; g->CurrentFunc = NULL ; inFunc = 1 ; } Line *oldLastLine = g_script.mLastLine; if ((g_script.LoadIncludedText(script) != OK) || !g_script.PreparseBlocks(oldLastLine->mNextLine)) { if (inFunc == 1 ) g->CurrentFunc = aFunc; return LOADING_FAILED; } if (!oldLastLine->mNextLine) //H30 - if no line was added, return return OK; g_script.PreparseIfElse(oldLastLine->mNextLine); SendMessage(g_hWnd, AHK_EXECUTE, (WPARAM)oldLastLine->mNextLine, (LPARAM)oldLastLine->mNextLine); if (inFunc == 1 ) g->CurrentFunc = aFunc ; Line *prevLine = g_script.mLastLine->mPrevLine; for(; prevLine != oldLastLine; prevLine = prevLine->mPrevLine) { delete prevLine->mNextLine; } oldLastLine->mNextLine = NULL; // return OK; } #endif // AUTOHOTKEYSC LPTSTR FuncTokenToString(ExprTokenType &aToken, LPTSTR aBuf) // Supports Type() VAR_NORMAL and VAR-CLIPBOARD. // Returns "" on failure to simplify logic in callers. Otherwise, it returns either aBuf (if aBuf was needed // for the conversion) or the token's own string. aBuf may be NULL, in which case the caller presumably knows // that this token is SYM_STRING or SYM_OPERAND (or caller wants "" back for anything other than those). // If aBuf is not NULL, caller has ensured that aBuf is at least MAX_NUMBER_SIZE in size. { switch (aToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. return aToken.var->Contents(); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). case SYM_STRING: case SYM_OPERAND: return aToken.marker; case SYM_INTEGER: if (aBuf) return ITOA64(aToken.value_int64, aBuf); //else continue on to return the default at the bottom. break; case SYM_FLOAT: if (aBuf) { sntprintf(aBuf, MAX_NUMBER_SIZE, g->FormatFloat, aToken.value_double); return aBuf; } //else continue on to return the default at the bottom. break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). //default: // Not an operand: continue on to return the default at the bottom. } return _T(""); } EXPORT LPTSTR ahkFunction(LPTSTR func, LPTSTR param1, LPTSTR param2, LPTSTR param3, LPTSTR param4, LPTSTR param5, LPTSTR param6, LPTSTR param7, LPTSTR param8, LPTSTR param9, LPTSTR param10) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. aFunc->mParam[0].var->Assign((LPTSTR )param1); // Assign parameter #1 if (aFunc->mParamCount > 1 && param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. aFunc->mParam[1].var->Assign((LPTSTR )param2); if (aFunc->mParamCount > 2 && param3 != NULL) // Assign parameter #3 { aFunc->mParam[2].var->Assign((LPTSTR )param3); if (aFunc->mParamCount > 3 && param4 != NULL) // Assign parameter #4 { aFunc->mParam[3].var->Assign((LPTSTR )param4); if (aFunc->mParamCount > 4 && param5 != NULL) // Assign parameter #5 { aFunc->mParam[4].var->Assign((LPTSTR )param5); if (aFunc->mParamCount > 5 && param6 != NULL) // Assign parameter #6 { aFunc->mParam[5].var->Assign((LPTSTR )param6); if (aFunc->mParamCount > 6 && param7 != NULL) // Assign parameter #7 { aFunc->mParam[6].var->Assign((LPTSTR )param7); if (aFunc->mParamCount > 7 && param8 != NULL) // Assign parameter #8 { aFunc->mParam[7].var->Assign((LPTSTR )param8); if (aFunc->mParamCount > 8 && param9 != NULL) // Assign parameter #9 { aFunc->mParam[8].var->Assign((LPTSTR )param9); if (aFunc->mParamCount > 9 && param10 != NULL) // Assign parameter #10 { aFunc->mParam[9].var->Assign((LPTSTR )param10); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_DLL, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.result_to_return_dll; } else return _T(""); } //H30 changed to not return anything since it is not used void callFuncDll(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. DEBUGGER_STACK_POP() switch (aFuncAndToken->mToken.symbol) { case SYM_VAR: // Caller has ensured that any SYM_VAR's Type() is VAR_NORMAL. if (_tcslen(aFuncAndToken->mToken.var->Contents())) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.var->Contents())*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.var->Contents()); // Contents() vs. mContents to support VAR_CLIPBOARD, and in case mContents needs to be updated by Contents(). } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_STRING: case SYM_OPERAND: if (_tcslen(aFuncAndToken->mToken.marker)) { aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,_tcslen(aFuncAndToken->mToken.marker)*sizeof(TCHAR)); _tcscpy(aFuncAndToken->result_to_return_dll,aFuncAndToken->mToken.marker); } else if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; break; case SYM_INTEGER: aFuncAndToken->result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); ITOA64(aFuncAndToken->mToken.value_int64, aFuncAndToken->result_to_return_dll); break; case SYM_FLOAT: result_to_return_dll = (LPTSTR )realloc((LPTSTR )aFuncAndToken->result_to_return_dll,MAX_INTEGER_LENGTH); sntprintf(aFuncAndToken->result_to_return_dll, MAX_NUMBER_SIZE, g->FormatFloat, aFuncAndToken->mToken.value_double); break; //case SYM_OBJECT: // L31: Treat objects as empty strings (or TRUE where appropriate). default: // Not an operand: continue on to return the default at the bottom. if (aFuncAndToken->result_to_return_dll) *aFuncAndToken->result_to_return_dll = '\0'; } //Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(ErrorLevel_saved); return; } void AssignVariant(Var &aArg, VARIANT &aVar, bool aRetainVar); VARIANT ahkFunctionVariant(LPTSTR func, VARIANT param1,/*[in,optional]*/ VARIANT param2,/*[in,optional]*/ VARIANT param3,/*[in,optional]*/ VARIANT param4,/*[in,optional]*/ VARIANT param5,/*[in,optional]*/ VARIANT param6,/*[in,optional]*/ VARIANT param7,/*[in,optional]*/ VARIANT param8,/*[in,optional]*/ VARIANT param9,/*[in,optional]*/ VARIANT param10, int sendOrPost) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { // g_script.mTempFunc = aFunc ; // ExprTokenType return_value; if (aFunc->mParamCount > 0 && &param1 != NULL) { // Copy the appropriate values into each of the function's formal parameters. AssignVariant(*aFunc->mParam[0].var, param1, false); // Assign parameter #1 if (aFunc->mParamCount > 1 && &param2 != NULL) // Assign parameter #2 { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. AssignVariant(*aFunc->mParam[1].var, param2, false); if (aFunc->mParamCount > 2 && &param3 != NULL) // Assign parameter #3 { AssignVariant(*aFunc->mParam[2].var, param3, false); if (aFunc->mParamCount > 3 && &param4 != NULL) // Assign parameter #4 { AssignVariant(*aFunc->mParam[3].var, param4, false); if (aFunc->mParamCount > 4 && &param5 != NULL) // Assign parameter #5 { AssignVariant(*aFunc->mParam[4].var, param5, false); if (aFunc->mParamCount > 5 && &param6 != NULL) // Assign parameter #6 { AssignVariant(*aFunc->mParam[5].var, param6, false); if (aFunc->mParamCount > 6 && &param7 != NULL) // Assign parameter #7 { AssignVariant(*aFunc->mParam[6].var, param7, false); if (aFunc->mParamCount > 7 && &param8 != NULL) // Assign parameter #8 { AssignVariant(*aFunc->mParam[7].var, param8, false); if (aFunc->mParamCount > 8 && &param9 != NULL) // Assign parameter #9 { AssignVariant(*aFunc->mParam[8].var, param9, false); if (aFunc->mParamCount > 9 && &param10 != NULL) // Assign parameter #10 { AssignVariant(*aFunc->mParam[9].var, param10, false); } } } } } } } } } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; aFuncAndToken.mFunc = aFunc ; returnCount++ ; if (returnCount > 9) returnCount = 0 ; if (sendOrPost == 1) { SendMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); return aFuncAndToken.variant_to_return_dll; } else { PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION_VARIANT, (WPARAM)&aFuncAndToken,NULL); VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; } } FuncAndToken & aFuncAndToken = aFuncAndTokenToReturn[returnCount]; returnCount++ ; VARIANT &r = aFuncAndToken.variant_to_return_dll; r.vt = VT_NULL ; return r ; // should return a blank variant } void TokenToVariant(ExprTokenType &aToken, VARIANT &aVar); void callFuncDllVariant(FuncAndToken *aFuncAndToken) { Func &func = *(aFuncAndToken->mFunc); ExprTokenType & aResultToken = aFuncAndToken->mToken ; // Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (g_nThreads >= MAX_THREADS_EMERGENCY // To avoid array overflow, this limit must by obeyed except where otherwise documented. || func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); DEBUGGER_STACK_PUSH(func.mJumpToLine, func.mName) // ExprTokenType aResultToken; // ExprTokenType &aResultToken = aResultToken_to_return ; func.Call(&aResultToken); // Call the UDF. TokenToVariant(aResultToken, aFuncAndToken->variant_to_return_dll); DEBUGGER_STACK_POP() ResumeUnderlyingThread(ErrorLevel_saved); return; } diff --git a/source/script.cpp b/source/script.cpp index 05e777d..a6da384 100644 --- a/source/script.cpp +++ b/source/script.cpp @@ -1,1625 +1,1632 @@ /* AutoHotkey Copyright 2003-2009 Chris Mallett ([email protected]) 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" // for a lot of things #include "util.h" // for strlcpy() etc. #include "mt19937ar-cok.h" // for random number generator #include "window.h" // for a lot of things #include "application.h" // for MsgSleep() #include "exports.h" // Naveen v8 #include "TextIO.h" #include "MemoryModule.h" // Globals that are for only this module: #define MAX_COMMENT_FLAG_LENGTH 15 static TCHAR g_CommentFlag[MAX_COMMENT_FLAG_LENGTH + 1] = _T(";"); // Adjust the below for any changes. static size_t g_CommentFlagLength = 1; // pre-calculated for performance static ExprOpFunc g_ObjGet(BIF_ObjInvoke, IT_GET), g_ObjSet(BIF_ObjInvoke, IT_SET), g_ObjCall(BIF_ObjInvoke, IT_CALL); static ExprOpFunc g_ObjGetInPlace(BIF_ObjGetInPlace, IT_GET); static TextMem::Buffer includedtextbuf; //HotKeyIt for dll to read script from memory // General note about the methods in here: // Want to be able to support multiple simultaneous points of execution // because more than one subroutine can be executing simultaneously // (well, more precisely, there can be more than one script subroutine // that's in a "currently running" state, even though all such subroutines, // except for the most recent one, are suspended. So keep this in mind when // using things such as static data members or static local variables. Script::Script() : mFirstLine(NULL), mLastLine(NULL), mCurrLine(NULL), mPlaceholderLabel(NULL), mFirstStaticLine(NULL), mLastStaticLine(NULL) #ifndef MINIDLL , mThisHotkeyName(_T("")), mPriorHotkeyName(_T("")), mThisHotkeyStartTime(0), mPriorHotkeyStartTime(0) , mEndChar(0), mThisHotkeyModifiersLR(0) #endif , mNextClipboardViewer(NULL), mOnClipboardChangeIsRunning(false), mOnClipboardChangeLabel(NULL) , mOnExitLabel(NULL), mExitReason(EXIT_NONE) , mFirstLabel(NULL), mLastLabel(NULL) , mFirstFunc(NULL), mLastFunc(NULL), mFunc(NULL), mFuncCount(0), mFuncCountMax(0) // L27: Removed mFirstFunc, added mFunc, mFuncCount, mFuncCountMax. L31: Re-enabled mFirstFunc. , mFirstTimer(NULL), mLastTimer(NULL), mTimerEnabledCount(0), mTimerCount(0) #ifndef MINIDLL , mFirstMenu(NULL), mLastMenu(NULL), mMenuCount(0) #endif , mVar(NULL), mVarCount(0), mVarCountMax(0), mLazyVar(NULL), mLazyVarCount(0) , mCurrentFuncOpenBlockCount(0), mNextLineIsFunctionBody(false) , mFuncExceptionVar(NULL), mFuncExceptionVarCount(0) , mCurrFileIndex(0), mCombinedLineNumber(0), mNoHotkeyLabels(true) #ifndef MINIDLL , mMenuUseErrorLevel(false) #endif , mFileSpec(_T("")), mFileDir(_T("")), mFileName(_T("")), mOurEXE(_T("")), mOurEXEDir(_T("")), mMainWindowTitle(_T("")) , mIsReadyToExecute(false), mAutoExecSectionIsRunning(false) , mIsRestart(false), mIsAutoIt2(false), mErrorStdOut(false) #ifdef AUTOHOTKEYSC , mCompiledHasCustomIcon(false) #else , mIncludeLibraryFunctionsThenExit(NULL) #endif , mLinesExecutedThisCycle(0), mUninterruptedLineCountMax(1000), mUninterruptibleTime(15) #ifndef MINIDLL , mCustomIcon(NULL), mCustomIconSmall(NULL) // Normally NULL unless there's a custom tray icon loaded dynamically. , mCustomIconFile(NULL), mIconFrozen(false), mTrayIconTip(NULL) // Allocated on first use. , mCustomIconNumber(0) #endif { // v1.0.25: mLastScriptRest and mLastPeekTime are now initialized right before the auto-exec // section of the script is launched, which avoids an initial Sleep(10) in ExecUntil // that would otherwise occur. #ifndef MINIDLL *mThisMenuItemName = *mThisMenuName = '\0'; #endif ZeroMemory(&mNIC, sizeof(mNIC)); // Constructor initializes this, to be safe. mNIC.hWnd = NULL; // Set this as an indicator that it tray icon is not installed. #ifndef MINIDLL // Lastly (after the above have been initialized), anything that can fail: if ( !(mTrayMenu = AddMenu(_T("Tray"))) ) // realistically never happens { ScriptError(_T("No tray mem")); ExitApp(EXIT_CRITICAL); } else mTrayMenu->mIncludeStandardItems = true; #endif #ifdef _DEBUG if (ID_FILE_EXIT < ID_MAIN_FIRST) // Not a very thorough check. ScriptError(_T("DEBUG: ID_FILE_EXIT is too large (conflicts with IDs reserved via ID_USER_FIRST).")); if (MAX_CONTROLS_PER_GUI > ID_USER_FIRST - 3) ScriptError(_T("DEBUG: MAX_CONTROLS_PER_GUI is too large (conflicts with IDs reserved via ID_USER_FIRST).")); int LargestMaxParams, i, j; ActionTypeType *np; // Find the Largest value of MaxParams used by any command and make sure it // isn't something larger than expected by the parsing routines: for (LargestMaxParams = i = 0; i < g_ActionCount; ++i) { if (g_act[i].MaxParams > LargestMaxParams) LargestMaxParams = g_act[i].MaxParams; // This next part has been tested and it does work, but only if one of the arrays // contains exactly MAX_NUMERIC_PARAMS number of elements and isn't zero terminated. // Relies on short-circuit boolean order: for (np = g_act[i].NumericParams, j = 0; j < MAX_NUMERIC_PARAMS && *np; ++j, ++np); if (j >= MAX_NUMERIC_PARAMS) { ScriptError(_T("DEBUG: At least one command has a NumericParams array that isn't zero-terminated.") _T(" This would result in reading beyond the bounds of the array.")); return; } } if (LargestMaxParams > MAX_ARGS) ScriptError(_T("DEBUG: At least one command supports more arguments than allowed.")); if (sizeof(ActionTypeType) == 1 && g_ActionCount > 256) ScriptError(_T("DEBUG: Since there are now more than 256 Action Types, the ActionTypeType") _T(" typedef must be changed.")); #endif #ifndef _USRDLL OleInitialize(NULL); #endif } Script::~Script() // Destructor. { // MSDN: "Before terminating, an application must call the UnhookWindowsHookEx function to free // system resources associated with the hook." #ifndef MINIDLL AddRemoveHooks(0); // Remove all hooks. if (mNIC.hWnd) // Tray icon is installed. Shell_NotifyIcon(NIM_DELETE, &mNIC); // Remove it. // Destroy any Progress/SplashImage windows that haven't already been destroyed. This is necessary // because sometimes these windows aren't owned by the main window: #endif int i; #ifndef MINIDLL for (i = 0; i < MAX_PROGRESS_WINDOWS; ++i) { if (g_Progress[i].hwnd && IsWindow(g_Progress[i].hwnd)) DestroyWindow(g_Progress[i].hwnd); if (g_Progress[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont1); if (g_Progress[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_Progress[i].hfont2); if (g_Progress[i].hbrush) DeleteObject(g_Progress[i].hbrush); } for (i = 0; i < MAX_SPLASHIMAGE_WINDOWS; ++i) { if (g_SplashImage[i].pic_bmp) { if (g_SplashImage[i].pic_type == IMAGE_BITMAP) DeleteObject(g_SplashImage[i].pic_bmp); else DestroyIcon(g_SplashImage[i].pic_icon); } if (g_SplashImage[i].hwnd && IsWindow(g_SplashImage[i].hwnd)) DestroyWindow(g_SplashImage[i].hwnd); if (g_SplashImage[i].hfont1) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont1); if (g_SplashImage[i].hfont2) // Destroy font only after destroying the window that uses it. DeleteObject(g_SplashImage[i].hfont2); if (g_SplashImage[i].hbrush) DeleteObject(g_SplashImage[i].hbrush); } // It is safer/easier to destroy the GUI windows prior to the menus (especially the menu bars). // This is because one GUI window might get destroyed and take with it a menu bar that is still // in use by an existing GUI window. GuiType::Destroy() adheres to this philosophy by detaching // its menu bar prior to destroying its window: for (i = 0; i < MAX_GUI_WINDOWS; ++i) GuiType::Destroy(i); // Static method to avoid problems with object destroying itself. for (i = 0; i < GuiType::sFontCount; ++i) // Now that GUI windows are gone, delete all GUI fonts. if (GuiType::sFont[i].hfont) DeleteObject(GuiType::sFont[i].hfont); // The above might attempt to delete an HFONT from GetStockObject(DEFAULT_GUI_FONT), etc. // But that should be harmless: // MSDN: "It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject." // Above: Probably best to have removed icon from tray and destroyed any Gui/Splash windows that were // using it prior to getting rid of the script's custom icon below: if (mCustomIcon) { DestroyIcon(mCustomIcon); DestroyIcon(mCustomIconSmall); // Should always be non-NULL if mCustomIcon is non-NULL. } // Since they're not associated with a window, we must free the resources for all popup menus. // Update: Even if a menu is being used as a GUI window's menu bar, see note above for why menu // destruction is done AFTER the GUI windows are destroyed: UserMenu *menu_to_delete; for (UserMenu *m = mFirstMenu; m;) { menu_to_delete = m; m = m->mNextMenu; ScriptDeleteMenu(menu_to_delete); // Above call should not return FAIL, since the only way FAIL can realistically happen is // when a GUI window is still using the menu as its menu bar. But all GUI windows are gone now. } #endif // Since tooltip windows are unowned, they should be destroyed to avoid resource leak: for (i = 0; i < MAX_TOOLTIPS; ++i) if (g_hWndToolTip[i] && IsWindow(g_hWndToolTip[i])) DestroyWindow(g_hWndToolTip[i]); #ifndef MINIDLL if (g_hFontSplash) // The splash window itself should auto-destroyed, since it's owned by main. DeleteObject(g_hFontSplash); #endif if (mOnClipboardChangeLabel) // Remove from viewer chain. ChangeClipboardChain(g_hWnd, mNextClipboardViewer); // Close any open sound item to prevent hang-on-exit in certain operating systems or conditions. // If there's any chance that a sound was played and not closed out, or that it is still playing, // this check is done. Otherwise, the check is avoided since it might be a high overhead call, // especially if the sound subsystem part of the OS is currently swapped out or something: if (g_SoundWasPlayed) { TCHAR buf[MAX_PATH * 2]; mciSendString(_T("status ") SOUNDPLAY_ALIAS _T(" mode"), buf, _countof(buf), NULL); if (*buf) // "playing" or "stopped" mciSendString(_T("close ") SOUNDPLAY_ALIAS, NULL, 0, NULL); } #ifndef MINIDLL #ifdef ENABLE_KEY_HISTORY_FILE KeyHistoryToFile(); // Close the KeyHistory file if it's open. #endif #endif // MINIDLL DeleteCriticalSection(&g_CriticalRegExCache); // g_CriticalRegExCache is used elsewhere for thread-safety. OleUninitialize(); } #ifdef _USRDLL void Script::Destroy() // HotKeyIt H1 destroy script for ahkTerminate and ahkReload and ExitApp for dll { /* //ExprTokenType aResultToken; static ExprTokenType **aParam = (ExprTokenType **)SimpleHeap::Malloc(sizeof(__int64));; ExprTokenType aThisParam[1]; aThisParam[0].symbol = SYM_STRING; aThisParam[0].marker = _T(""); aParam[0] = aThisParam; int aParamCount = 0; BIF_DynaCall(aThisParam[0], aParam, aParamCount); */ // L31: Release objects stored in variables, where possible. int v, i; for (v = 0; v < mVarCount; ++v) { // H19 fix not to delete Clipboard wars if (mVar[v]->mType == VAR_BUILTIN ||mVar[v]->mType == VAR_CLIPBOARD ||mVar[v]->mType == VAR_CLIPBOARDALL) continue; mVar[v]->ConvertToNonAliasIfNecessary(); + if (mVar[v]->IsObject()) + mVar[v]->ReleaseObject(); mVar[v]->Free(); } for (v = 0; v < mLazyVarCount; ++v) { mLazyVar[v]->ConvertToNonAliasIfNecessary(); + if (mLazyVar[v]->IsObject()) + mLazyVar[v]->ReleaseObject(); mLazyVar[v]->Free(); } for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) + { + f.mVar[v]->ConvertToNonAliasIfNecessary(); + if (f.mVar[v]->IsObject()) + f.mVar[v]->ReleaseObject(); f.mVar[v]->Free(); + } for (v = 0; v < f.mLazyVarCount; ++v) + { + f.mLazyVar[v]->ConvertToNonAliasIfNecessary(); + if (f.mLazyVar[v]->IsObject()) + f.mLazyVar[v]->ReleaseObject(); f.mLazyVar[v]->Free(); - for (v = 0; v < f.mLazyVarCount; ++v) - f.mLazyVar[v]->Free(); + } delete mFunc[i]; } // Destroy Labels for (Label *label = mFirstLabel; label != NULL;label = label->mNextLabel) { Label *nextLabel = label->mNextLabel; label->mJumpToLine = NULL; label->mName = _T(""); label->mPrevLabel = NULL; } /* for (Line *line = g_script.mFirstLine; line != NULL;) { Line *nextLine = line->mNextLine; delete line; line = nextLine; } */ mFirstFunc = NULL; mFuncCount = 0; mFirstLabel = NULL ; mLastLabel = NULL ; mLastFunc = NULL ; mFirstStaticLine = 0; mLastStaticLine = 0; mFirstLine = NULL ; mLastLine = NULL ; mCurrLine = NULL ; mCurrFileIndex = 0 ; #ifndef MINIDLL mFirstMenu = NULL; #endif mFirstTimer = NULL; mIsReadyToExecute = false; mOnExitLabel = NULL; mOnClipboardChangeLabel = NULL; mTempFunc = NULL; mTempLabel = NULL; mTempLine = NULL; Line::sSourceFileCount = 0; // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: KILL_AUTOEXEC_TIMER KILL_MAIN_TIMER if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } #ifndef MINIDLL AddRemoveHooks(0); Hotkey::AllDestruct(); Hotstring::AllDestruct(); #endif Script::~Script(); g_script.mIsReadyToExecute = false; + global_clear_state(*g); } #endif -#ifdef ENABLE_KEY_HISTORY_FILE - KeyHistoryToFile(); // Close the KeyHistory file if it's open. -#endif ResultType Script::Init(global_struct &g, LPTSTR aScriptFilename, bool aIsRestart, HINSTANCE hInstance, bool aIsText) // Returns OK or FAIL. // Caller has provided an empty string for aScriptFilename if this is a compiled script. // Otherwise, aScriptFilename can be NULL if caller hasn't determined the filename of the script yet. { mIsRestart = aIsRestart; TCHAR buf[2048]; // Just to make sure we have plenty of room to do things with. #ifdef AUTOHOTKEYSC // Fix for v1.0.29: Override the caller's use of __argv[0] by using GetModuleFileName(), // so that when the script is started from the command line but the user didn't type the // extension, the extension will be included. This necessary because otherwise // #SingleInstance wouldn't be able to detect duplicate versions in every case. // It also provides more consistency. GetModuleFileName(NULL, buf, _countof(buf)); #else if (!aScriptFilename) // v1.0.46.08: Change in policy: store the default script in the My Documents directory rather than in Program Files. It's more correct and solves issues that occur due to Vista's file-protection scheme. { TCHAR ahkinibuf[MAX_PATH+1]; // HotKeyIt changed to load ahk file having same name as AutoHotkey.exe from same directory instead AutoHotkey.ahk from My_Documents aScriptFilename = ahkinibuf; BIV_AhkPath(aScriptFilename,_T("")); #ifdef STANDALONE BIV_AhkPath(aScriptFilename,_T("")); #else // Since no script-file was specified on the command line, use the default name. // For backward compatibility, FIRST check if there's an AutoHotkey.ini file in the current // directory. If there is, that needs to be used to retain compatibility. _tcsncpy(aScriptFilename + _tcslen(aScriptFilename) - 3,_T("ahk"),3); if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { _tcsncpy(aScriptFilename + _tcslen(aScriptFilename) - 3,_T("ini"),3); if (GetFileAttributes(aScriptFilename) == 0xFFFFFFFF) // File doesn't exist, so fall back to new method. { // aScriptFilename = buf; VarSizeType filespec_length = BIV_MyDocuments(aScriptFilename, _T("")); // e.g. C:\Documents and Settings\Home\My Documents if (filespec_length > _countof(buf)-16) // Need room for 16 characters ('\\' + "AutoHotkey.ahk" + terminator). return FAIL; // Very rare, so for simplicity just abort. _tcscpy(aScriptFilename + filespec_length, _T("\\AutoHotkey.ahk")); // Append the filename: .ahk vs. .ini seems slightly better in terms of clarity and usefulness (e.g. the ability to double click the default script to launch it). // Now everything is set up right because even if aScriptFilename is a nonexistent file, the // user will be prompted to create it by a stage further below. } //else since the legacy .ini file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) } //else since the .ahk file exists, everything is now set up right. (The file might be a directory, but that isn't checked due to rarity.) #endif } // In case the script is a relative filespec (relative to current working dir): if (hInstance != NULL && aIsText) //It is a dll and script was given as text rather than file { if (!GetModuleFileName(hInstance, buf, _countof(buf))) //Get dll path GetModuleFileName(NULL, buf, _countof(buf)); //due to MemoryLoadLibrary dll path might be empty } else if (!GetFullPathName(aScriptFilename, _countof(buf), buf, NULL)) // This is also relied upon by mIncludeLibraryFunctionsThenExit. Succeeds even on nonexistent files. return FAIL; // Due to rarity, no error msg, just abort. #endif // Using the correct case not only makes it look better in title bar & tray tool tip, // it also helps with the detection of "this script already running" since otherwise // it might not find the dupe if the same script name is launched with different // lowercase/uppercase letters: ConvertFilespecToCorrectCase(buf); // This might change the length, e.g. due to expansion of 8.3 filename. LPTSTR filename_marker; if ( !(filename_marker = _tcsrchr(buf, '\\')) ) filename_marker = buf; else ++filename_marker; if ( !(mFileSpec = SimpleHeap::Malloc(buf)) ) // The full spec is stored for convenience, and it's relied upon by mIncludeLibraryFunctionsThenExit. return FAIL; // It already displayed the error for us. filename_marker[-1] = '\0'; // Terminate buf in this position to divide the string. size_t filename_length = _tcslen(filename_marker); #ifndef _USRDLL if ( mIsAutoIt2 = (filename_length >= 4 && !_tcsicmp(filename_marker + filename_length - 4, EXT_AUTOIT2)) ) { // Set the old/AutoIt2 defaults for maximum safety and compatibilility. // Standalone EXEs (compiled scripts) are always considered to be non-AutoIt2 (otherwise, // the user should probably be using the AutoIt2 compiler). g_AllowSameLineComments = false; g_EscapeChar = '\\'; g.TitleFindFast = true; // In case the normal default is false. g.DetectHiddenText = false; // Make the mouse fast like AutoIt2, but not quite insta-move. 2 is expected to be more // reliable than 1 since the AutoIt author said that values less than 2 might cause the // drag to fail (perhaps just for specific apps, such as games): g.DefaultMouseSpeed = 2; g.KeyDelay = 20; g.WinDelay = 500; g.LinesPerCycle = 1; g.IntervalBeforeRest = -1; // i.e. this method is disabled by default for AutoIt2 scripts. // Reduce max params so that any non escaped delimiters the user may be using literally // in "window text" will still be considered literal, rather than as delimiters for // args that are not supported by AutoIt2, such as exclude-title, exclude-text, MsgBox // timeout, etc. Note: Don't need to change IfWinExist and such because those already // have special handling to recognize whether exclude-title is really a valid command // instead (e.g. IfWinExist, title, text, Gosub, something). // NOTE: DO NOT ADD the IfWin command series to this section, since there is special handling // for parsing those commands to figure out whether they're being used in the old AutoIt2 // style or the new Exclude Title/Text mode. // v1.0.40.02: The following is no longer done because a different mechanism is required now // that the ARGn macros do not check whether mArgc is too small and substitute an empty string // (instead, there is a loop in ExpandArgs that puts an empty string in each sArgDeref entry // for which the script omitted a parameter [and that loop relies on MaxParams being absolutely // accurate rather than conditional upon whether the script is of type ".aut"]). //g_act[ACT_FILESELECTFILE].MaxParams -= 2; //g_act[ACT_FILEREMOVEDIR].MaxParams -= 1; //g_act[ACT_MSGBOX].MaxParams -= 1; //g_act[ACT_INIREAD].MaxParams -= 1; //g_act[ACT_STRINGREPLACE].MaxParams -= 1; //g_act[ACT_STRINGGETPOS].MaxParams -= 2; //g_act[ACT_WINCLOSE].MaxParams -= 3; // -3 for these two, -2 for the others. //g_act[ACT_WINKILL].MaxParams -= 3; //g_act[ACT_WINACTIVATE].MaxParams -= 2; //g_act[ACT_WINMINIMIZE].MaxParams -= 2; //g_act[ACT_WINMAXIMIZE].MaxParams -= 2; //g_act[ACT_WINRESTORE].MaxParams -= 2; //g_act[ACT_WINHIDE].MaxParams -= 2; //g_act[ACT_WINSHOW].MaxParams -= 2; //g_act[ACT_WINSETTITLE].MaxParams -= 2; //g_act[ACT_WINGETTITLE].MaxParams -= 2; } #endif if ( !(mFileDir = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. if ( !(mFileName = SimpleHeap::Malloc(filename_marker)) ) return FAIL; // It already displayed the error for us. #ifdef AUTOHOTKEYSC // Omit AutoHotkey from the window title, like AutoIt3 does for its compiled scripts. // One reason for this is to reduce backlash if evil-doers create viruses and such // with the program: sntprintf(buf, _countof(buf), _T("%s\\%s"), mFileDir, mFileName); #else sntprintf(buf, _countof(buf), _T("%s\\%s - %s"), mFileDir, mFileName, T_AHK_NAME_VERSION); #endif if ( !(mMainWindowTitle = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. // It may be better to get the module name this way rather than reading it from the registry // (though it might be more proper to parse it out of the command line args or something), // in case the user has moved it to a folder other than the install folder, hasn't installed it, // or has renamed the EXE file itself. Also, enclose the full filespec of the module in double // quotes since that's how callers usually want it because ActionExec() currently needs it that way: *buf = '"'; if (GetModuleFileName(NULL, buf + 1, _countof(buf) - 2)) // -2 to leave room for the enclosing double quotes. { size_t buf_length = _tcslen(buf); buf[buf_length++] = '"'; buf[buf_length] = '\0'; if ( !(mOurEXE = SimpleHeap::Malloc(buf)) ) return FAIL; // It already displayed the error for us. else { LPTSTR last_backslash = _tcsrchr(buf, '\\'); if (!last_backslash) // probably can't happen due to the nature of GetModuleFileName(). mOurEXEDir = _T(""); last_backslash[1] = '\0'; // i.e. keep the trailing backslash for convenience. if ( !(mOurEXEDir = SimpleHeap::Malloc(buf + 1)) ) // +1 to omit the leading double-quote. return FAIL; // It already displayed the error for us. } } return OK; } ResultType Script::CreateWindows() // Returns OK or FAIL. { if (!mMainWindowTitle || !*mMainWindowTitle) return FAIL; // Init() must be called before this function. // Register a window class for the main window: WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = WINDOW_CLASS_MAIN; wc.hInstance = g_hInstance; wc.lpfnWndProc = MainWindowProc; // The following are left at the default of NULL/0 set higher above: //wc.style = 0; // CS_HREDRAW | CS_VREDRAW //wc.cbClsExtra = 0; //wc.cbWndExtra = 0; #ifndef MINIDLL wc.hIcon = wc.hIconSm = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_MAIN), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). wc.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); // Needed for ProgressBar. Old: (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_MAIN); // NULL; // "MainMenu"; #endif #ifdef UNICODE UnregisterClass((LPCWSTR)&WINDOW_CLASS_MAIN,g_hInstance); #else UnregisterClass((LPCSTR)&WINDOW_CLASS_MAIN,g_hInstance); #endif if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } // Register a second class for the splash window. The only difference is that // it doesn't have the menu bar: #ifndef MINIDLL wc.lpszClassName = WINDOW_CLASS_SPLASH; wc.lpszMenuName = NULL; // Override the non-NULL value set higher above. #ifdef UNICODE UnregisterClass((LPCWSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #else UnregisterClass((LPCSTR)&WINDOW_CLASS_SPLASH,g_hInstance); #endif if (!RegisterClassEx(&wc)) { MsgBox(_T("RegClass")); // Short/generic msg since so rare. return FAIL; } #endif TCHAR class_name[64]; HWND fore_win = GetForegroundWindow(); bool do_minimize = !fore_win || (GetClassName(fore_win, class_name, _countof(class_name)) && !_tcsicmp(class_name, _T("Shell_TrayWnd"))); // Shell_TrayWnd is the taskbar's class on Win98/XP and probably the others too. // Note: the title below must be constructed the same was as is done by our // WinMain() (so that we can detect whether this script is already running) // which is why it's standardized in g_script.mMainWindowTitle. // Create the main window. Prevent momentary disruption of Start Menu, which // some users understandably don't like, by omitting the taskbar button temporarily. // This is done because testing shows that minimizing the window further below, even // though the window is hidden, would otherwise briefly show the taskbar button (or // at least redraw the taskbar). Sometimes this isn't noticeable, but other times // (such as when the system is under heavy load) a user reported that it is quite // noticeable. WS_EX_TOOLWINDOW is used instead of WS_EX_NOACTIVATE because // WS_EX_NOACTIVATE is available only on 2000/XP. if ( !(g_hWnd = CreateWindowEx(do_minimize ? WS_EX_TOOLWINDOW : 0 , WINDOW_CLASS_MAIN , mMainWindowTitle , WS_OVERLAPPEDWINDOW // Style. Alt: WS_POPUP or maybe 0. , CW_USEDEFAULT // xpos , CW_USEDEFAULT // ypos , CW_USEDEFAULT // width , CW_USEDEFAULT // height , NULL // parent window , NULL // Identifies a menu, or specifies a child-window identifier depending on the window style , g_hInstance // passed into WinMain , NULL)) ) // lpParam { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } #ifdef AUTOHOTKEYSC HMENU menu = GetMenu(g_hWnd); // Disable the Edit menu item, since it does nothing for a compiled script: EnableMenuItem(menu, ID_FILE_EDITSCRIPT, MF_DISABLED | MF_GRAYED); EnableOrDisableViewMenuItems(menu, MF_DISABLED | MF_GRAYED); // Fix for v1.0.47.06: No point in checking g_AllowMainWindow because the script hasn't starting running yet, so it will always be false. // But leave the ID_VIEW_REFRESH menu item enabled because if the script contains a // command such as ListLines in it, Refresh can be validly used. #endif if ( !(g_hWndEdit = CreateWindow(_T("edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL // | WS_HSCROLL (saves space) , 0, 0, 0, 0, g_hWnd, (HMENU)1, g_hInstance, NULL)) ) { MsgBox(_T("CreateWindow")); // Short msg since so rare. return FAIL; } // FONTS: The font used by default, at least on XP, is GetStockObject(SYSTEM_FONT). // It seems preferable to smaller fonts such DEFAULT_GUI_FONT(DEFAULT_GUI_FONT). // For more info on pre-loaded fonts (not too many choices), see MSDN's GetStockObject(). if(g_os.IsWinNT()) { // Use a more appealing font on NT versions of Windows. // Windows NT to Windows XP -> Lucida Console HDC hdc = GetDC(g_hWndEdit); if(!g_os.IsWinVistaOrLater()) g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Lucida Console")); else // Windows Vista and later -> Consolas g_hFontEdit = CreateFont(FONT_POINT(hdc, 10), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Consolas")); ReleaseDC(g_hWndEdit, hdc); // In theory it must be done. SendMessage(g_hWndEdit, WM_SETFONT, (WPARAM)g_hFontEdit, 0); } // v1.0.30.05: Specifying a limit of zero opens the control to its maximum text capacity, // which removes the 32K size restriction. Testing shows that this does not increase the actual // amount of memory used for controls containing small amounts of text. All it does is allow // the control to allocate more memory as needed. By specifying zero, a max // of 64K becomes available on Windows 9x, and perhaps as much as 4 GB on NT/2k/XP. SendMessage(g_hWndEdit, EM_LIMITTEXT, 0, 0); // Some of the MSDN docs mention that an app's very first call to ShowWindow() makes that // function operate in a special mode. Therefore, it seems best to get that first call out // of the way to avoid the possibility that the first-call behavior will cause problems with // our normal use of ShowWindow() below and other places. Also, decided to ignore nCmdShow, // to avoid any momentary visual effects on startup. // Update: It's done a second time because the main window might now be visible if the process // that launched ours specified that. It seems best to override the requested state because // some calling processes might specify "maximize" or "shownormal" as generic launch method. // The script can display it's own main window with ListLines, etc. // MSDN: "the nCmdShow value is ignored in the first call to ShowWindow if the program that // launched the application specifies startup information in the structure. In this case, // ShowWindow uses the information specified in the STARTUPINFO structure to show the window. // On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT // to use the startup information provided by the program that launched the application." ShowWindow(g_hWnd, SW_HIDE); ShowWindow(g_hWnd, SW_HIDE); // Now that the first call to ShowWindow() is out of the way, minimize the main window so that // if the script is launched from the Start Menu (and perhaps other places such as the // Quick-launch toolbar), the window that was active before the Start Menu was displayed will // become active again. But as of v1.0.25.09, this minimize is done more selectively to prevent // the launch of a script from knocking the user out of a full-screen game or other application // that would be disrupted by an SW_MINIMIZE: if (do_minimize) { ShowWindow(g_hWnd, SW_MINIMIZE); SetWindowLong(g_hWnd, GWL_EXSTYLE, 0); // Give the main window back its taskbar button. } // Note: When the window is not minimized, task manager reports that a simple script (such as // one consisting only of the single line "#Persistent") uses 2600 KB of memory vs. ~452 KB if // it were immediately minimized. That is probably just due to the vagaries of how the OS // manages windows and memory and probably doesn't actually impact system performance to the // degree indicated. In other words, it's hard to imagine that the failure to do // ShowWidnow(g_hWnd, SW_MINIMIZE) unconditionally upon startup (which causes the side effects // discussed further above) significantly increases the actual memory load on the system. g_hAccelTable = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); #ifndef MINIDLL if (g_NoTrayIcon) #endif mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. #ifndef MINIDLL else // Even if the below fails, don't return FAIL in case the user is using a different shell // or something. In other words, it is expected to fail under certain circumstances and // we want to tolerate that: CreateTrayIcon(); #endif if (mOnClipboardChangeLabel) mNextClipboardViewer = SetClipboardViewer(g_hWnd); return OK; } #ifndef MINIDLL void Script::EnableOrDisableViewMenuItems(HMENU aMenu, UINT aFlags) { EnableMenuItem(aMenu, ID_VIEW_KEYHISTORY, aFlags); EnableMenuItem(aMenu, ID_VIEW_LINES, aFlags); EnableMenuItem(aMenu, ID_VIEW_VARIABLES, aFlags); EnableMenuItem(aMenu, ID_VIEW_HOTKEYS, aFlags); } void Script::CreateTrayIcon() // It is the caller's responsibility to ensure that the previous icon is first freed/destroyed // before calling us to install a new one. However, that is probably not needed if the Explorer // crashed, since the memory used by the tray icon was probably destroyed along with it. { ZeroMemory(&mNIC, sizeof(mNIC)); // To be safe. // Using NOTIFYICONDATA_V2_SIZE vs. sizeof(NOTIFYICONDATA) improves compatibility with Win9x maybe. // MSDN: "Using [NOTIFYICONDATA_V2_SIZE] for cbSize will allow your application to use NOTIFYICONDATA // with earlier Shell32.dll versions, although without the version 6.0 enhancements." // Update: Using V2 gives an compile error so trying V1. Update: Trying sizeof(NOTIFYICONDATA) // for compatibility with VC++ 6.x. This is also what AutoIt3 uses: mNIC.cbSize = sizeof(NOTIFYICONDATA); // NOTIFYICONDATA_V1_SIZE mNIC.hWnd = g_hWnd; mNIC.uID = AHK_NOTIFYICON; // This is also used for the ID, see TRANSLATE_AHK_MSG for details. mNIC.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; mNIC.uCallbackMessage = AHK_NOTIFYICON; #ifdef AUTOHOTKEYSC // i.e. don't override the user's custom icon: mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); #else // L17: Always use small icon for tray. mNIC.hIcon = mCustomIconSmall ? mCustomIconSmall : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(g_IconTray), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED to conserve memory (since the main icon is loaded for so many purposes). #endif UPDATE_TIP_FIELD // If we were called due to an Explorer crash, I don't think it's necessary to call // Shell_NotifyIcon() to remove the old tray icon because it was likely destroyed // along with Explorer. So just add it unconditionally: if (!Shell_NotifyIcon(NIM_ADD, &mNIC)) mNIC.hWnd = NULL; // Set this as an indicator that tray icon is not installed. } void Script::UpdateTrayIcon(bool aForceUpdate) { if (!mNIC.hWnd) // tray icon is not installed return; static bool icon_shows_paused = false; static bool icon_shows_suspended = false; if (!aForceUpdate && (mIconFrozen || (g->IsPaused == icon_shows_paused && g_IsSuspended == icon_shows_suspended))) return; // it's already in the right state int icon; if (g->IsPaused && g_IsSuspended) icon = IDI_PAUSE_SUSPEND; else if (g->IsPaused) icon = IDI_PAUSE; else if (g_IsSuspended) icon = g_IconTraySuspend; else #ifdef AUTOHOTKEYSC icon = mCompiledHasCustomIcon ? IDI_MAIN : g_IconTray; // i.e. don't override the user's custom icon. #else icon = g_IconTray; #endif // Use the custom tray icon if the icon is normal (non-paused & non-suspended): mNIC.hIcon = (mCustomIconSmall && (mIconFrozen || (!g->IsPaused && !g_IsSuspended))) ? mCustomIconSmall // L17: Always use small icon for tray. : (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(icon), IMAGE_ICON, 0, 0, LR_SHARED); // Use LR_SHARED for simplicity and performance more than to conserve memory in this case. if (Shell_NotifyIcon(NIM_MODIFY, &mNIC)) { icon_shows_paused = g->IsPaused; icon_shows_suspended = g_IsSuspended; } // else do nothing, just leave it in the same state. } #endif ResultType Script::AutoExecSection() // Returns FAIL if can't run due to critical error. Otherwise returns OK. { // Now that g_MaxThreadsTotal has been permanently set by the processing of script directives like // #MaxThreads, an appropriately sized array can be allocated: if ( !(g_array = (global_struct *)malloc((g_MaxThreadsTotal+TOTAL_ADDITIONAL_THREADS) * sizeof(global_struct))) ) return FAIL; // Due to rarity, just abort. It wouldn't be safe to run ExitApp() due to possibility of an OnExit routine. CopyMemory(g_array, g, sizeof(global_struct)); // Copy the temporary/startup "g" into array[0] to preserve historical behaviors that may rely on the idle thread starting with that "g". g = g_array; // Must be done after above. // v1.0.48: Due to switching from SET_UNINTERRUPTIBLE_TIMER to IsInterruptible(): // In spite of the comments in IsInterruptible(), periodically have a timer call IsInterruptible() due to // the following scenario: // - Interrupt timeout is 60 seconds (or 60 milliseconds for that matter). // - For some reason IsInterrupt() isn't called for 24+ hours even though there is a current/active thread. // - RefreshInterruptibility() fires at 23 hours and marks the thread interruptible. // - Sometime after that, one of the following happens: // Computer is suspended/hibernated and stays that way for 50+ days. // IsInterrupt() is never called (except by RefreshInterruptibility()) for 50+ days. // (above is currently unlikely because MSG_FILTER_MAX calls IsInterruptible()) // In either case, RefreshInterruptibility() has prevented the uninterruptibility duration from being // wrongly extended by up to 100% of g_script.mUninterruptibleTime. This isn't a big deal if // g_script.mUninterruptibleTime is low (like it almost always is); but if it's fairly large, say an hour, // this can prevent an unwanted extension of up to 1 hour. // Although any call frequency less than 49.7 days should work, currently calling once per 23 hours // in case any older operating systems have a SetTimer() limit of less than 0x7FFFFFFF (and also to make // it less likely that a long suspend/hibernate would cause the above issue). The following was // actually tested on Windows XP and a message does indeed arrive 23 hours after the script starts. SetTimer(g_hWnd, TIMER_ID_REFRESH_INTERRUPTIBILITY, 23*60*60*1000, RefreshInterruptibility); // 3rd param must not exceed 0x7FFFFFFF (2147483647; 24.8 days). ResultType ExecUntil_result; if (!mFirstLine) // In case it's ever possible to be empty. ExecUntil_result = OK; // And continue on to do normal exit routine so that the right ExitCode is returned by the program. else { // Choose a timeout that's a reasonable compromise between the following competing priorities: // 1) That we want hotkeys to be responsive as soon as possible after the program launches // in case the user launches by pressing ENTER on a script, for example, and then immediately // tries to use a hotkey. In addition, we want any timed subroutines to start running ASAP // because in rare cases the user might rely upon that happening. // 2) To support the case when the auto-execute section never finishes (such as when it contains // an infinite loop to do background processing), yet we still want to allow the script // to put custom defaults into effect globally (for things such as KeyDelay). // Obviously, the above approach has its flaws; there are ways to construct a script that would // result in unexpected behavior. However, the combination of this approach with the fact that // the global defaults are updated *again* when/if the auto-execute section finally completes // raises the expectation of proper behavior to a very high level. In any case, I'm not sure there // is any better approach that wouldn't break existing scripts or require a redesign of some kind. // If this method proves unreliable due to disk activity slowing the program down to a crawl during // the critical milliseconds after launch, one thing that might fix that is to have ExecUntil() // be forced to run a minimum of, say, 100 lines (if there are that many) before allowing the // timer expiration to have its effect. But that's getting complicated and I'd rather not do it // unless someone actually reports that such a thing ever happens. Still, to reduce the chance // of such a thing ever happening, it seems best to boost the timeout from 50 up to 100: SET_AUTOEXEC_TIMER(100); mAutoExecSectionIsRunning = true; // v1.0.25: This is now done here, closer to the actual execution of the first line in the script, // to avoid an unnecessary Sleep(10) that would otherwise occur in ExecUntil: mLastScriptRest = mLastPeekTime = GetTickCount(); ++g_nThreads; DEBUGGER_STACK_PUSH(mFirstLine, _T("auto-execute")) ExecUntil_result = mFirstLine->ExecUntil(UNTIL_RETURN); // Might never return (e.g. infinite loop or ExitApp). DEBUGGER_STACK_POP() --g_nThreads; // Our caller will take care of setting g_default properly. KILL_AUTOEXEC_TIMER // See also: AutoExecSectionTimeout(). mAutoExecSectionIsRunning = false; } // REMEMBER: The ExecUntil() call above will never return if the AutoExec section never finishes // (e.g. infinite loop) or it uses Exit/ExitApp. // The below is done even if AutoExecSectionTimeout() already set the values once. // This is because when the AutoExecute section finally does finish, by definition it's // supposed to store the global settings that are currently in effect as the default values. // In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where // the AutoExecute section takes a long time to complete, or never completes (perhaps because // it is being used by the script as a "backround thread" of sorts): // Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part // of the script. These new defaults will be put into effect whenever a new hotkey subroutine // is launched. Each launched subroutine may then change the values for its own purposes without // affecting the settings for other subroutines: global_clear_state(*g); // Start with a "clean slate" in both g_default and g (in case things like InitNewThread() check some of the values in g prior to launching a new thread). // Always want g_default.AllowInterruption==true so that InitNewThread() doesn't have to // set it except when Critical or "Thread Interrupt" require it. If the auto-execute section ended // without anyone needing to call IsInterruptible() on it, AllowInterruption could be false // even when Critical is off. // Even if the still-running AutoExec section has turned on Critical, the assignment below is still okay // because InitNewThread() adjusts AllowInterruption based on the value of ThreadIsCritical. // See similar code in AutoExecSectionTimeout(). g->AllowThreadToBeInterrupted = true; // Mostly for the g_default line below. See comments above. CopyMemory(&g_default, g, sizeof(global_struct)); // g->IsPaused has been set to false higher above in case it's ever possible that it's true as a result of AutoExecSection(). // After this point, the values in g_default should never be changed. global_maximize_interruptibility(*g); // See below. // Now that any changes made by the AutoExec section have been saved to g_default (including // the commands Critical and Thread), ensure that the very first g-item is always interruptible. // This avoids having to treat the first g-item as special in various places. // It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done. // However, it isn't set to NONE right before launching each new thread (e.g. hotkey subroutine) // because it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value // of ErrorLevel set by another). This reset was also done by LoadFromFile(), but it is done again // here in case the auto-execute section changed it: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // BEFORE DOING THE BELOW, "g" and "g_default" should be set up properly in case there's an OnExit // routine (even non-persistent scripts can have one). // If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script // doesn't contain the #Persistent directive we're done unless there is an OnExit subroutine and it // doesn't do "ExitApp": if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time. g_script.ExitApp(ExecUntil_result == FAIL ? EXIT_ERROR : EXIT_EXIT); return OK; } #ifndef MINIDLL ResultType Script::Edit() { #ifdef AUTOHOTKEYSC return OK; // Do nothing. #else // This is here in case a compiled script ever uses the Edit command. Since the "Edit This // Script" menu item is not available for compiled scripts, it can't be called from there. TitleMatchModes old_mode = g->TitleMatchMode; g->TitleMatchMode = FIND_ANYWHERE; HWND hwnd = WinExist(*g, mFileName, _T(""), mMainWindowTitle, _T("")); // Exclude our own main window. g->TitleMatchMode = old_mode; if (hwnd) { TCHAR class_name[32]; GetClassName(hwnd, class_name, _countof(class_name)); if (!_tcscmp(class_name, _T("#32770")) || !_tcsnicmp(class_name, _T("AutoHotkey"), 10)) // MessageBox(), InputBox(), FileSelectFile(), or GUI/script-owned window. hwnd = NULL; // Exclude it from consideration. } if (hwnd) // File appears to already be open for editing, so use the current window. SetForegroundWindowEx(hwnd); else { TCHAR buf[MAX_PATH * 2]; // Enclose in double quotes anything that might contain spaces since the CreateProcess() // method, which is attempted first, is more likely to succeed. This is because it uses // the command line method of creating the process, with everything all lumped together: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) // Since this didn't work, try notepad. { // v1.0.40.06: Try to open .ini files first with their associated editor rather than trying the // "edit" verb on them: LPTSTR file_ext; if ( !(file_ext = _tcsrchr(mFileName, '.')) || _tcsicmp(file_ext, _T(".ini")) || !ActionExec(_T("open"), buf, mFileDir, false) ) // Relies on short-circuit boolean order. { // Even though notepad properly handles filenames with spaces in them under WinXP, // even without double quotes around them, it seems safer and more correct to always // enclose the filename in double quotes for maximum compatibility with all OSes: if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) MsgBox(_T("Could not open script.")); // Short message since so rare. } } } return OK; #endif } #endif // MINIDLL ResultType Script::Reload(bool aDisplayErrors) { // The new instance we're about to start will tell our process to stop, or it will display // a syntax error or some other error, in which case our process will still be running: #ifdef _USRDLL reloadDll(); return EARLY_RETURN; #else #ifdef AUTOHOTKEYSC // This is here in case a compiled script ever uses the Reload command. Since the "Reload This // Script" menu item is not available for compiled scripts, it can't be called from there. return g_script.ActionExec(mOurEXE, _T("/restart"), g_WorkingDirOrig, aDisplayErrors); #else TCHAR arg_string[MAX_PATH + 512]; sntprintf(arg_string, _countof(arg_string), _T("/restart \"%s\""), mFileSpec); return g_script.ActionExec(mOurEXE, arg_string, g_WorkingDirOrig, aDisplayErrors); #endif // AUTOHOTKEYSC #endif // _USRDLL } ResultType Script::ExitApp(ExitReasons aExitReason, LPTSTR aBuf, int aExitCode) // Normal exit (if aBuf is NULL), or a way to exit immediately on error (which is mostly // for times when it would be unsafe to call MsgBox() due to the possibility that it would // make the situation even worse). { mExitReason = aExitReason; bool terminate_afterward = aBuf && !*aBuf; if (aBuf && *aBuf) { TCHAR buf[1024]; // No more than size-1 chars will be written and string will be terminated: sntprintf(buf, _countof(buf), _T("Critical Error: %s\n\n") WILL_EXIT, aBuf); // To avoid chance of more errors, don't use MsgBox(): MessageBox(g_hWnd, buf, g_script.mFileSpec, MB_OK | MB_SETFOREGROUND | MB_APPLMODAL); TerminateApp(aExitReason, CRITICAL_ERROR); // Only after the above. } // Otherwise, it's not a critical error. Note that currently, mOnExitLabel can only be // non-NULL if the script is in a runnable state (since registering an OnExit label requires // that a script command has executed to do it). If this ever changes, the !mIsReadyToExecute // condition should be added to the below if statement: static bool sExitLabelIsRunning = false; if (!mOnExitLabel || sExitLabelIsRunning) // || !mIsReadyToExecute { // In the case of sExitLabelIsRunning == true: // There is another instance of this function beneath us on the stack. Since we have // been called, this is a true exit condition and we exit immediately. // MUST NOT create a new thread when sExitLabelIsRunning because g_array allows only one // extra thread for ExitApp() (which allows it to run even when MAX_THREADS_EMERGENCY has // been reached). See TOTAL_ADDITIONAL_THREADS. g_AllowInterruption = FALSE; // In case TerminateApp releases objects and indirectly causes g->IsPaused = false; // more script to be executed. TerminateApp(aExitReason, aExitCode); } // Otherwise, the script contains the special RunOnExit label that we will run here instead // of exiting. And since it does, we know that the script is in a ready-to-execute state // because that is the only way an OnExit label could have been defined in the first place. // Usually, the RunOnExit subroutine will contain an Exit or ExitApp statement // which results in a recursive call to this function, but this is not required (e.g. the // Exit subroutine could display an "Are you sure?" prompt, and if the user chooses "No", // the Exit sequence can be aborted by simply not calling ExitApp and letting the thread // we create below end normally). // Next, save the current state of the globals so that they can be restored just prior // to returning to our caller: TCHAR ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; tcslcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), _countof(ErrorLevel_saved)); // Save caller's errorlevel. InitNewThread(0, true, true, ACT_INVALID); // Uninterruptibility is handled below. Since this special thread should always run, no checking of g_MaxThreadsTotal is done before calling this. // Turn on uninterruptibility to forbid any hotkeys, timers, or user defined menu items // to interrupt. This is mainly done for peace-of-mind (since possible interactions due to // interruptions have not been studied) and the fact that this most users would not want this // subroutine to be interruptible (it usually runs quickly anyway). Another reason to make // it non-interruptible is that some OnExit subroutines might destruct things used by the // script's hotkeys/timers/menu items, and activating these items during the deconstruction // would not be safe. Finally, if a logoff or shutdown is occurring, it seems best to prevent // timed subroutines from running -- which might take too much time and prevent the exit from // occurring in a timely fashion. An option can be added via the FutureUse param to make it // interruptible if there is ever a demand for that. // UPDATE: g_AllowInterruption is now used instead of g->AllowThreadToBeInterrupted for two reasons: // 1) It avoids the need to do "int mUninterruptedLineCountMax_prev = g_script.mUninterruptedLineCountMax;" // (Disable this item so that ExecUntil() won't automatically make our new thread uninterruptible // after it has executed a certain number of lines). // 2) Mostly obsolete: If the thread we're interrupting is uninterruptible, the uinterruptible timer // might be currently pending. When it fires, it would make the OnExit subroutine interruptible // rather than the underlying subroutine. The above fixes the first part of that problem. // The 2nd part is fixed by reinstating the timer when the uninterruptible thread is resumed. // This special handling is only necessary here -- not in other places where new threads are // created -- because OnExit is the only type of thread that can interrupt an uninterruptible // thread. BOOL g_AllowInterruption_prev = g_AllowInterruption; // Save current setting. g_AllowInterruption = FALSE; // Mark the thread just created above as permanently uninterruptible (i.e. until it finishes and is destroyed). sExitLabelIsRunning = true; DEBUGGER_STACK_PUSH(mOnExitLabel->mJumpToLine, mOnExitLabel->mName) if (mOnExitLabel->Execute() == FAIL) { // If the subroutine encounters a failure condition such as a runtime error, exit immediately. // Otherwise, there will be no way to exit the script if the subroutine fails on each attempt. TerminateApp(aExitReason, aExitCode); } DEBUGGER_STACK_POP() sExitLabelIsRunning = false; // In case the user wanted the thread to end normally (see above). if (terminate_afterward) TerminateApp(aExitReason, aExitCode); // Otherwise: ResumeUnderlyingThread(ErrorLevel_saved); g_AllowInterruption = g_AllowInterruption_prev; // Restore original setting. return OK; // for caller convenience. } void Script::TerminateApp(ExitReasons aExitReason, int aExitCode) // Note that g_script's destructor takes care of most other cleanup work, such as destroying // tray icons, menus, and unowned windows such as ToolTip. { #ifdef _USRDLL terminateDll(); - return; #else // L31: Release objects stored in variables, where possible. if (aExitCode != CRITICAL_ERROR) // i.e. Avoid making matters worse if CRITICAL_ERROR. { int v, i; for (v = 0; v < mVarCount; ++v) if (mVar[v]->IsObject()) mVar[v]->ReleaseObject(); for (v = 0; v < mLazyVarCount; ++v) if (mLazyVar[v]->IsObject()) mLazyVar[v]->ReleaseObject(); for (i = 0; i < mFuncCount; ++i) { Func &f = *mFunc[i]; if (f.mIsBuiltIn) continue; // Since it doesn't seem feasible to release all var backups created by recursive function // calls and all tokens in the 'stack' of each currently executing expression, currently // only static and global variables are released. It seems best for consistency to also // avoid releasing top-level non-static local variables (i.e. which aren't in var backups). for (v = 0; v < f.mVarCount; ++v) if (f.mVar[v]->IsStatic() && f.mVar[v]->IsObject()) // For consistency, only free static vars (see above). f.mVar[v]->ReleaseObject(); for (v = 0; v < f.mLazyVarCount; ++v) if (f.mLazyVar[v]->IsStatic() && f.mLazyVar[v]->IsObject()) f.mLazyVar[v]->ReleaseObject(); } } #ifdef CONFIG_DEBUGGER // L34: Exit debugger *after* the above to allow debugging of any invoked __Delete handlers. g_Debugger.Exit(aExitReason); #endif // We call DestroyWindow() because MainWindowProc() has left that up to us. // DestroyWindow() will cause MainWindowProc() to immediately receive and process the // WM_DESTROY msg, which should in turn result in any child windows being destroyed // and other cleanup being done: if (IsWindow(g_hWnd)) // Adds peace of mind in case WM_DESTROY was already received in some unusual way. { g_DestroyWindowCalled = true; DestroyWindow(g_hWnd); } -#ifndef MINIDLL Hotkey::AllDestructAndExit(aExitCode); #endif -#endif } #ifndef AUTOHOTKEYSC LineNumberType Script::LoadFromText(LPTSTR aScript) // HotKeyIt H1 LoadFromText() for text instead LoadFromFile() // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedText(aScript) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { #ifndef MINIDLL // Check for any unprocessed #if expressions: for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above calls. // Use FindOrAdd, not Add, because the user may already have added it simply by // referring to it in the script: if ( !(g_ErrorLevel = FindOrAddVar(_T("ErrorLevel"))) ) return LOADING_FAILED; // Error. Above already displayed it for us. // Initialize the var state to zero right before running anything in the script: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Initialize the random number generator: // Note: On 32-bit hardware, the generator module uses only 2506 bytes of static // data, so it doesn't seem worthwhile to put it in a class (so that the mem is // only allocated on first use of the generator). For v1.0.24, _ftime() is not // used since it could be as large as 0.5 KB of non-compressed code. A simple call to // GetSystemTimeAsFileTime() seems just as good or better, since it produces // a FILETIME, which is "the number of 100-nanosecond intervals since January 1, 1601." // Use the low-order DWORD since the high-order one rarely changes. If my calculations are correct, // the low-order 32-bits traverses its full 32-bit range every 7.2 minutes, which seems to make // using it as a seed superior to GetTickCount for most purposes. RESEED_RANDOM_GENERATOR; return TRUE; // Must be non-zero. // OBSOLETE: mLineCount was always non-zero at this point since above did AddLine(). //return mLineCount; // The count of runnable lines that were loaded, which might be zero. } #endif #ifdef AUTOHOTKEYSC UINT Script::LoadFromFile() #else UINT Script::LoadFromFile(bool aScriptWasNotspecified) #endif // Returns the number of non-comment lines that were loaded, or LOADING_FAILED on error. { mNoHotkeyLabels = true; // Indicate that there are no hotkey labels, since we're (re)loading the entire file. mIsReadyToExecute = mAutoExecSectionIsRunning = false; if (!mFileSpec || !*mFileSpec) return LOADING_FAILED; #ifndef AUTOHOTKEYSC // When not in stand-alone mode, read an external script file. DWORD attr = GetFileAttributes(mFileSpec); if (attr == MAXDWORD) // File does not exist or lacking the authorization to get its attributes. { #ifdef MINIDLL return LOADING_FAILED; #endif TCHAR buf[MAX_PATH + 256]; if (aScriptWasNotspecified) // v1.0.46.09: Give a more descriptive prompt to help users get started. { sntprintf(buf, _countof(buf), _T("To help you get started, would you like to create a sample script in the My Documents folder?\n") _T("\n") _T("Press YES to create and display the sample script.\n") _T("Press NO to exit.\n")); } else // Mostly for backward compatibility, also prompt to create if an explicitly specified script doesn't exist. sntprintf(buf, _countof(buf), _T("The script file \"%s\" does not exist. Create it now?"), mFileSpec); int response = MsgBox(buf, MB_YESNO); if (response != IDYES) return 0; FILE *fp2 = _tfopen(mFileSpec, _T("a")); if (!fp2) { MsgBox(_T("Could not create file, perhaps because the current directory is read-only") _T(" or has insufficient permissions.")); return LOADING_FAILED; } _fputts( _T("; IMPORTANT INFO ABOUT GETTING STARTED: Lines that start with a\n") _T("; semicolon, such as this one, are comments. They are not executed.\n") _T("\n") _T("; This script has a special filename and path because it is automatically\n") _T("; launched when you run the program directly. Also, any text file whose\n") _T("; name ends in .ahk is associated with the program, which means that it\n") _T("; can be launched simply by double-clicking it. You can have as many .ahk\n") _T("; files as you want, located in any folder. You can also run more than\n") _T("; one .ahk file simultaneously and each will get its own tray icon.\n") _T("\n") _T("; SAMPLE HOTKEYS: Below are two sample hotkeys. The first is Win+Z and it\n") _T("; launches a web site in the default browser. The second is Control+Alt+N\n") _T("; and it launches a new Notepad window (or activates an existing one). To\n") _T("; try out these hotkeys, run AutoHotkey again, which will load this file.\n") _T("\n") _T("#z::Run www.autohotkey.com\n") _T("\n") _T("^!n::\n") _T("IfWinExist Untitled - Notepad\n") _T("\tWinActivate\n") _T("else\n") _T("\tRun Notepad\n") _T("return\n") _T("\n") _T("\n") _T("; Note: From now on whenever you run AutoHotkey directly, this script\n") _T("; will be loaded. So feel free to customize it to suit your needs.\n") _T("\n") _T("; Please read the QUICK-START TUTORIAL near the top of the help file.\n") _T("; It explains how to perform common automation tasks such as sending\n") _T("; keystrokes and mouse clicks. It also explains more about hotkeys.\n") , fp2); fclose(fp2); // One or both of the below would probably fail -- at least on Win95 -- if mFileSpec ever // has spaces in it (since it's passed as the entire param string). So enclose the filename // in double quotes. I don't believe the directory needs to be in double quotes since it's // a separate field within the CreateProcess() and ShellExecute() structures: sntprintf(buf, _countof(buf), _T("\"%s\""), mFileSpec); if (!ActionExec(_T("edit"), buf, mFileDir, false)) if (!ActionExec(_T("notepad.exe"), buf, mFileDir, false)) { MsgBox(_T("Can't open script.")); // Short msg since so rare. return LOADING_FAILED; } // future: have it wait for the process to close, then try to open the script again: return 0; } #endif // v1.0.42: Placeholder to use in place of a NULL label to simplify code in some places. // This must be created before loading the script because it's relied upon when creating // hotkeys to provide an alternative to having a NULL label. It will be given a non-NULL // mJumpToLine further down. if ( !(mPlaceholderLabel = new Label(_T(""))) ) // Not added to linked list since it's never looked up. return LOADING_FAILED; // L4: Changed this next section to support lines added for #if (expression). // Each #if (expression) is pre-parsed *before* the main script in order for // function library auto-inclusions to be processed correctly. // Load the main script file. This will also load any files it includes with #Include. if ( LoadIncludedFile(mFileSpec, false, false) != OK || !AddLine(ACT_EXIT)) // Fix for v1.0.47.04: Add an Exit because otherwise, a script that ends in an IF-statement will crash in PreparseBlocks() because PreparseBlocks() expects every IF-statements mNextLine to be non-NULL (helps loading performance too). return LOADING_FAILED; // BELOW: Aside from setting up {} blocks, PreparseBlocks() resolves function references in expressions. // Originally PreparseBlocks() resolved all function references in one sweep. Since func lib auto-inclusions // are appended to the main script, they were automatically handled by a later iteration of the loop inside // PreparseBlocks(). However, the introduction of #If and Static initializers bring some complications: // (a) Function-calls in the main script, #If expressions or Static initializers can cause auto-inclusions. // (b) Auto-inclusions can introduce more function-calls. // (c) Auto-inclusions can introduce more #If expressions or Static initializers. // The loop below handles these potentially "recursive" cases. Line *last_line_processed = NULL, *last_static_processed = NULL; int expr_line_index = 0; for (;;) { // Check for any unprocessed #if expressions: #ifndef MINIDLL for ( ; expr_line_index < g_HotExprLineCount; ++expr_line_index) { Line *line = g_HotExprLines[expr_line_index]; if (!PreparseBlocks(line)) return LOADING_FAILED; // Search for "ACT_EXPRESSION will be changed to ACT_IFEXPR" for comments about the following line: line->mActionType = ACT_IFEXPR; } #endif // Check for any unprocessed static initializers: if (last_static_processed != mLastStaticLine) { if (!PreparseBlocks(last_static_processed ? last_static_processed->mNextLine : mFirstStaticLine)) return LOADING_FAILED; last_static_processed = mLastStaticLine; } // Check for any unprocessed lines in the main script: if (last_line_processed != mLastLine) { if (!PreparseBlocks(last_line_processed ? last_line_processed->mNextLine : mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above call. last_line_processed = mLastLine; } // Since #If expressions and Static initializers can't directly bring about more #If expressions or Static // initializers, the fact that no new lines have been added to the script since the last iteration means // all lines in the main script, all #If expressions and all Static initializers have been processed. else break; } // ABOVE: In v1.0.47, the above may have auto-included additional files from the userlib/stdlib. // That's why the above is done prior to adding the EXIT lines and other things below. if (mFirstStaticLine) { // Prepend all Static initializers to the beginning of the auto-execute section. mLastStaticLine->mNextLine = mFirstLine; mFirstLine->mPrevLine = mLastStaticLine; mFirstLine = mFirstStaticLine; } if (g_Warn_LocalSameAsGlobal) { // Scan all "automatic" local vars and warn the user if there are any with the same // name as a global variable, since that would probably indicate a missing declaration: int i, j; Func *func; for (i = 0; i < mFuncCount; ++i) { if (!(func = mFunc[i])->mIsBuiltIn) { for (j = 0; j < func->mVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mVar[j]); for (j = 0; j < func->mLazyVarCount; ++j) MaybeWarnLocalSameAsGlobal(func, func->mLazyVar[j]); } } } #ifndef AUTOHOTKEYSC if (mIncludeLibraryFunctionsThenExit) { delete mIncludeLibraryFunctionsThenExit; return 0; // Tell our caller to do a normal exit. } #endif // v1.0.35.11: Restore original working directory so that changes made to it by the above (via // "#Include C:\Scripts" or "#Include %A_ScriptDir%" or even stdlib/userlib) do not affect the // script's runtime working directory. This preserves the flexibility of having a startup-determined // working directory for the script's runtime (i.e. it seems best that the mere presence of // "#Include NewDir" should not entirely eliminate this flexibility). SetCurrentDirectory(g_WorkingDirOrig); // g_WorkingDirOrig previously set by WinMain(). // Rather than do this, which seems kinda nasty if ever someday support same-line // else actions such as "else return", just add two EXITs to the end of every script. // That way, if the first EXIT added accidentally "corrects" an actionless ELSE // or IF, the second one will serve as the anchoring end-point (mRelatedLine) for that // IF or ELSE. In other words, since we never want mRelatedLine to be NULL, this should // make absolutely sure of that: //if (mLastLine->mActionType == ACT_ELSE || // ACT_IS_IF(mLastLine->mActionType) // ... // Second ACT_EXIT: even if the last line of the script is already "exit", always add // another one in case the script ends in a label. That way, every label will have // a non-NULL target, which simplifies other aspects of script execution. // Making sure that all scripts end with an EXIT ensures that if the script // file ends with ELSEless IF or an ELSE, that IF's or ELSE's mRelatedLine // will be non-NULL, which further simplifies script execution. // Not done since it's number doesn't much matter: ++mCombinedLineNumber; ++mCombinedLineNumber; // So that the EXITs will both show up in ListLines as the line # after the last physical one in the script. if (!(AddLine(ACT_EXIT) && AddLine(ACT_EXIT))) // Second exit guaranties non-NULL mRelatedLine(s). return LOADING_FAILED; mPlaceholderLabel->mJumpToLine = mLastLine; // To follow the rule "all labels should have a non-NULL line before the script starts running". if (!PreparseIfElse(mFirstLine)) return LOADING_FAILED; // Error was already displayed by the above calls. // Use FindOrAdd, not Add, because the user may already have added it simply by // referring to it in the script: if ( !(g_ErrorLevel = FindOrAddVar(_T("ErrorLevel"))) ) return LOADING_FAILED; // Error. Above already displayed it for us. // Initialize the var state to zero right before running anything in the script: g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Initialize the random number generator: // Note: On 32-bit hardware, the generator module uses only 2506 bytes of static // data, so it doesn't seem worthwhile to put it in a class (so that the mem is // only allocated on first use of the generator). For v1.0.24, _ftime() is not // used since it could be as large as 0.5 KB of non-compressed code. A simple call to // GetSystemTimeAsFileTime() seems just as good or better, since it produces // a FILETIME, which is "the number of 100-nanosecond intervals since January 1, 1601." // Use the low-order DWORD since the high-order one rarely changes. If my calculations are correct, // the low-order 32-bits traverses its full 32-bit range every 7.2 minutes, which seems to make // using it as a seed superior to GetTickCount for most purposes. RESEED_RANDOM_GENERATOR; return TRUE; // Must be non-zero. // OBSOLETE: mLineCount was always non-zero at this point since above did AddLine(). //return mLineCount; // The count of runnable lines that were loaded, which might be zero. } bool IsFunction(LPTSTR aBuf, bool *aPendingFunctionHasBrace = NULL) // Helper function for LoadIncludedFile(). // Caller passes in an aBuf containing a candidate line such as "function(x, y)" // Caller has ensured that aBuf is rtrim'd. // Caller should pass NULL for aPendingFunctionHasBrace to indicate that function definitions (open-brace // on same line as function) are not allowed. When non-NULL *and* aBuf is a function call/def, // *aPendingFunctionHasBrace is set to true if a brace is present at the end, or false otherwise. // In addition, any open-brace is removed from aBuf in this mode. { LPTSTR action_end = StrChrAny(aBuf, EXPR_ALL_SYMBOLS EXPR_ILLEGAL_CHARS); // Can't be a function definition or call without an open-parenthesis as first char found by the above. // In addition, if action_end isn't NULL, that confirms that the string in aBuf prior to action_end contains // no spaces, tabs, colons, or equal-signs. As a result, it can't be: // 1) a hotstring, since they always start with at least one colon that would be caught immediately as // first-expr-char-is-not-open-parenthesis by the above. // 2) Any kind of math or assignment, such as var:=(x+y) or var+=(x+y). // The only things it could be other than a function call or function definition are: // Normal label that ends in single colon but contains an open-parenthesis prior to the colon, e.g. Label(x): // Single-line hotkey such as KeyName::MsgBox. But since '(' isn't valid inside KeyName, this isn't a concern. // In addition, note that it isn't necessary to check for colons that lie outside of quoted strings because // we're only interested in the first "word" of aBuf: If this is indeed a function call or definition, what // lies to the left of its first open-parenthesis can't contain any colons anyway because the above would // have caught it as first-expr-char-is-not-open-parenthesis. In other words, there's no way for a function's // opening parenthesis to occur after a legtimate/quoted colon or double-colon in its parameters. // v1.0.40.04: Added condition "action_end != aBuf" to allow a hotkey or remap or hotkey such as // such as "(::" to work even if it ends in a close-parenthesis such as "(::)" or "(::MsgBox )" if ( !(action_end && *action_end == '(' && action_end != aBuf && tcslicmp(aBuf, _T("IF"), action_end - aBuf) && tcslicmp(aBuf, _T("WHILE"), action_end - aBuf)) // v1.0.48.04: Recognize While() as loop rather than a function because many programmers are in the habit of writing while() and if(). || action_end[1] == ':' ) // v1.0.44.07: This prevents "$(::fn_call()" from being seen as a function-call vs. hotkey-with-call. For simplicity and due to rarity, omit_leading_whitespace() isn't called; i.e. assumes that the colon immediate follows the '('. return false; LPTSTR aBuf_last_char = action_end + _tcslen(action_end) - 1; // Above has already ensured that action_end is "(...". if (aPendingFunctionHasBrace) // Caller specified that an optional open-brace may be present at the end of aBuf. { if (*aPendingFunctionHasBrace = (*aBuf_last_char == '{')) // Caller has ensured that aBuf is rtrim'd. { *aBuf_last_char = '\0'; // For the caller, remove it from further consideration. aBuf_last_char = aBuf + rtrim(aBuf, aBuf_last_char - aBuf) - 1; // Omit trailing whitespace too. } } return *aBuf_last_char == ')'; // This last check avoids detecting a label such as "Label(x):" as a function. // Also, it seems best never to allow if(...) to be a function call, even if it's blank inside such as if(). // In addition, it seems best not to allow if(...) to ever be a function definition since such a function // could never be called as ACT_EXPRESSION since it would be seen as an IF-stmt instead. } #ifndef AUTOHOTKEYSC ResultType Script::LoadIncludedText(LPTSTR aFileSpec) // Returns OK or FAIL. // 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 { if (!aFileSpec || !*aFileSpec) return FAIL; // Keep this var on the stack due to recursion, which allows newly created lines to be given the // correct file number even when some #include's have been encountered in the middle of the script: int source_file_index = Line::sSourceFileCount; if (Line::sSourceFileCount >= Line::sMaxSourceFiles) { int new_max; if (Line::sMaxSourceFiles) { new_max = 2*Line::sMaxSourceFiles; if (new_max > ABSOLUTE_MAX_SOURCE_FILES) new_max = ABSOLUTE_MAX_SOURCE_FILES; } else new_max = 100; // For simplicity and due to rarity of every needing to, expand by reallocating the array. // Use a temp var. because realloc() returns NULL on failure but leaves original block allocated. LPTSTR *realloc_temp = (LPTSTR *)realloc(Line::sSourceFile, new_max * sizeof(LPTSTR)); // If passed NULL, realloc() will do a malloc(). if (!realloc_temp) return ScriptError(ERR_OUTOFMEM); // Short msg since so rare. Line::sSourceFile = realloc_temp; Line::sMaxSourceFiles = new_max; } if (!source_file_index) // Since this is the first source file, it must be the main script file. Just point it to the // location of the filespec already dynamically allocated: Line::sSourceFile[source_file_index] = aFileSpec; // <buf> should be no larger than LINE_SIZE because some later functions rely upon that: TCHAR msg_text[MAX_PATH + 256], buf1[LINE_SIZE], buf2[LINE_SIZE], suffix[16], pending_function[LINE_SIZE] = _T(""); LPTSTR buf = buf1, next_buf = buf2; // Oscillate between bufs to improve performance (avoids memcpy from buf2 to buf1). size_t buf_length, next_buf_length, suffix_length; bool pending_function_has_brace; ++Line::sSourceFileCount; includedtextbuf.mBuffer = aFileSpec; includedtextbuf.mLength = (DWORD)(_tcslen(aFileSpec) * sizeof(TCHAR)); includedtextbuf.mOwned = false; TextMem tmem, *fp = &tmem; // NOTE: Ahk2Exe strips off the UTF-8 BOM. //tmem.Open(textbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR, CP_UTF16); tmem.Open(includedtextbuf, TextStream::READ | TextStream::EOL_CRLF | TextStream::EOL_ORPHAN_CR #ifdef UNICODE , CP_UTF16 #endif ); // File is now open, read lines from it. #ifndef MINIDLL LPTSTR hotkey_flag, cp, cp1, action_end, hotstring_start, hotstring_options; Hotkey *hk; #else LPTSTR hotkey_flag, cp, action_end; #endif LineNumberType pending_function_line_number, saved_line_number; #ifndef MINIDLL HookActionType hook_action; bool is_label, suffix_has_tilde, in_comment_section, hotstring_options_all_valid; #else bool is_label, in_comment_section; #endif #ifndef MINIDLL
mikehelmick/SIGCSE2011-Web-Site
8de766743ebeffb5b7e3e0bd23177f96e173906e
add evaluations link
diff --git a/parts/main_right.php b/parts/main_right.php index db9f446..a896ad4 100644 --- a/parts/main_right.php +++ b/parts/main_right.php @@ -1,14 +1,13 @@ <h2>News</h2> <ul> - <li>The following workshops have been canceled: #25, #28, #31, #32, #34.</li> - <li>New event for 2011! <a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html">Robot Hoedown and Rodeo</a>. No experience necessary, but if you have robots and experience, <a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">we could use you as a wrangler</a>!</li> + <li><strong>Evaluations:</strong> Please take a moment to <a href="/sigcse2011/attendees/evaluations.php">fill out the SIGCSE 2011 symposium evaluation</a></li> </ul> <h2>Connect</h2> <ul> <li>Twitter: <a href="http://twitter.com/sigcse2011">twitter.com/sigcse2011</a> <ul><li>Tag your tweets with <code>#sigcse</code></li></ul> </li> <li>Facebook: <a href="http://www.facebook.com/group.php?gid=373261951323">SIGCSE 2011 Group</a></li> <li>Flickr: <a href="http://www.flickr.com/groups/sigcse2011/">Share your photos!</a></li> </ul> diff --git a/parts/today.php b/parts/today.php index ea1f1f1..d7b0dba 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,7 +1,8 @@ <div class="GoodMessage"> <p><strong>Post symposium updates</strong><br/><ul> + <li><strong>Evaluations:</strong> Please take a moment to <a href="/sigcse2011/attendees/evaluations.php">fill out the SIGCSE 2011 symposium evaluation</a></li> <li>Presentation slides from Matthias Felleisen's keynote can be <a href="http://www.ccs.neu.edu/home/matthias/presentations.html">found on his Web site</a></li> <li><a href="http://www.youtube.com/watch?v=ZfNzjzIB31Q&hd=1">Video of the Robot hoedown finale</a></li> <li>The robot hoedown even <a href="http://video.dallas.cbslocal.com/global/video/flash/popupplayer.asp?ClipID1=5651076&h1=Through%20The%20Lens:%20Learning%20To%20Make%20Robots%20Dance&vt1=v&at1=Technology&d1=116167&LaunchPageAdTag=Homepage&activePane=info&rnd=79321418">made the local news</a>!</li> </ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
326661585a7b23eb2de025779cb0300215623353
news updates
diff --git a/parts/today.php b/parts/today.php index 0159d4b..ea1f1f1 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,15 +1,7 @@ <div class="GoodMessage"> -<p><strong>Saturday March 12th at SIGCSE 2011</strong><br/><ul> -<li>Please take a few minutes to <a href="/sigcse2011/attendees/evaluations.php">fill out the SIGCSE 2011 symposium evaluation</a>. Thank you for your participation.</li> -<li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Saturday">Saturday's full program</a></li> -<li>Keynote: Luis Von Ahn, 12:30pm (<em>luncheon</em>). <a href="/sigcse2011/attendees/keynotes.php#saturday">Three Human Computation Projects</a> in Dallas BCD</li> -<li><strong>Robot Hoedown and Rodeo</strong><ul> - <li>Robot Hoedown Finale, Outside of Dallas A, 12:10 - 12:30pm</li> - <li><a href="http://elvis.rowan.edu/~kay/sigcse/media.html">Photos and Videos</a></li> -</ul></li> -<li><strong>Room Changes</strong><ul> - <li>10:55-12:10 Intro CS: Panoptic Views is moving from Dallas D2 to <strong>Lone Star A1</strong></li> - <li>10:55-12:10 Software Design and Development is moving from Dallas D1 to <strong>Dallas A3</strong></li> -</ul></li> +<p><strong>Post symposium updates</strong><br/><ul> + <li>Presentation slides from Matthias Felleisen's keynote can be <a href="http://www.ccs.neu.edu/home/matthias/presentations.html">found on his Web site</a></li> + <li><a href="http://www.youtube.com/watch?v=ZfNzjzIB31Q&hd=1">Video of the Robot hoedown finale</a></li> + <li>The robot hoedown even <a href="http://video.dallas.cbslocal.com/global/video/flash/popupplayer.asp?ClipID1=5651076&h1=Through%20The%20Lens:%20Learning%20To%20Make%20Robots%20Dance&vt1=v&at1=Technology&d1=116167&LaunchPageAdTag=Homepage&activePane=info&rnd=79321418">made the local news</a>!</li> </ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
ec57aa41c63b9d1dd43b683a16556f111f552a78
add robot hoedown links to saturday highlights
diff --git a/parts/today.php b/parts/today.php index 828be47..0159d4b 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,11 +1,15 @@ <div class="GoodMessage"> <p><strong>Saturday March 12th at SIGCSE 2011</strong><br/><ul> <li>Please take a few minutes to <a href="/sigcse2011/attendees/evaluations.php">fill out the SIGCSE 2011 symposium evaluation</a>. Thank you for your participation.</li> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Saturday">Saturday's full program</a></li> <li>Keynote: Luis Von Ahn, 12:30pm (<em>luncheon</em>). <a href="/sigcse2011/attendees/keynotes.php#saturday">Three Human Computation Projects</a> in Dallas BCD</li> +<li><strong>Robot Hoedown and Rodeo</strong><ul> + <li>Robot Hoedown Finale, Outside of Dallas A, 12:10 - 12:30pm</li> + <li><a href="http://elvis.rowan.edu/~kay/sigcse/media.html">Photos and Videos</a></li> +</ul></li> <li><strong>Room Changes</strong><ul> <li>10:55-12:10 Intro CS: Panoptic Views is moving from Dallas D2 to <strong>Lone Star A1</strong></li> <li>10:55-12:10 Software Design and Development is moving from Dallas D1 to <strong>Dallas A3</strong></li> </ul></li> </ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
e193159f1a9b359394f8a1a5e794124953d3119d
add evaluations to saturday highlights
diff --git a/parts/today.php b/parts/today.php index 5ece369..828be47 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,10 +1,11 @@ <div class="GoodMessage"> <p><strong>Saturday March 12th at SIGCSE 2011</strong><br/><ul> +<li>Please take a few minutes to <a href="/sigcse2011/attendees/evaluations.php">fill out the SIGCSE 2011 symposium evaluation</a>. Thank you for your participation.</li> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Saturday">Saturday's full program</a></li> <li>Keynote: Luis Von Ahn, 12:30pm (<em>luncheon</em>). <a href="/sigcse2011/attendees/keynotes.php#saturday">Three Human Computation Projects</a> in Dallas BCD</li> <li><strong>Room Changes</strong><ul> <li>10:55-12:10 Intro CS: Panoptic Views is moving from Dallas D2 to <strong>Lone Star A1</strong></li> <li>10:55-12:10 Software Design and Development is moving from Dallas D1 to <strong>Dallas A3</strong></li> </ul></li> </ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
15868fecdac33eb2e52b59bc5bb0c0f7d0713953
add saturday highlights
diff --git a/parts/today.php b/parts/today.php index 5ab05f3..1853344 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,7 +1,18 @@ <div class="GoodMessage"> <p><strong>Friday March 11th at SIGCSE 2011</strong><br/><ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Friday">Friday's full program</a></li> <li>Keynote: Susan Landau, 8:30am. <a href="/sigcse2011/attendees/keynotes.php#friday">A Computer Scientist Goes to Washington: How to be Effective in a World Where Facts are 10% of the Equation</a> in Dallas BC</li> <li><a href="http://upe.acm.org/">UPE national meeting</a>, 2011 Abacus Award Presentation and Talk: Donald Knuth (12:45-1:35pm)</li> </ul></p> +</div> + +<div class="GoodMessage"> +<p><strong>Saturday March 12th at SIGCSE 2011</strong><br/><ul> +<li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Saturday">Saturday's full program</a></li> +<li>Keynote: Luis Von Ahn, 12:30pm (<em>luncheon</em>). <a href="/sigcse2011/attendees/keynotes.php#saturday">Three Human Computation Projects</a> in Dallas BCD</li> +<li><strong>Room Changes</strong><ul> + <li>10:55-12:10 Intro CS: Panoptic Views is moving from Dallas D2 to <strong>Lone Star A1</strong></li> + <li>10:55-12:10 Software Design and Development is moving from Dallas D1 to <strong>Dallas A3</strong></li> +</ul></li> +</ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
fd5399207206ab61010b10a06289d518c13db09d
add highlights for friday
diff --git a/parts/today.php b/parts/today.php index ad6eb5f..5ab05f3 100644 --- a/parts/today.php +++ b/parts/today.php @@ -1,9 +1,7 @@ <div class="GoodMessage"> -<p><strong>Thursday March 10th at SIGCSE 2011</strong><br/><ul> -<li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Thursday">Thursday's full program</a></li> -<li>Keynote: Matthias Felleisen, 8:30am. <a href="/sigcse2011/attendees/keynotes.php#thursday">TeachScheme!</a> in Dallas BC</li> -<li>Paper sessions start at 10:45am today</li> -<li>First timers lunch, 12pm in Lone Star A1</li> -<li>Find your way around with <a href="/sigcse2011/attendees/floor_plans.php">floor plans</a></li> +<p><strong>Friday March 11th at SIGCSE 2011</strong><br/><ul> +<li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Friday">Friday's full program</a></li> +<li>Keynote: Susan Landau, 8:30am. <a href="/sigcse2011/attendees/keynotes.php#friday">A Computer Scientist Goes to Washington: How to be Effective in a World Where Facts are 10% of the Equation</a> in Dallas BC</li> +<li><a href="http://upe.acm.org/">UPE national meeting</a>, 2011 Abacus Award Presentation and Talk: Donald Knuth (12:45-1:35pm)</li> </ul></p> </div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
7d482428b4927e4f9191299cf4e49c3905e70e0e
add 'today' section and details for thursday
diff --git a/attendees/index.php b/attendees/index.php index 0e8d905..8c23cbe 100644 --- a/attendees/index.php +++ b/attendees/index.php @@ -1,64 +1,66 @@ <?php $title = "SIGCSE 2011 - Information for Symposium Attendees"; $menu = "attendees"; $submenu = "cfp"; include("../parts/top.php"); ?> <!-- <h2>Important Dates</h2> --> + +<?php include("../parts/today.php"); ?> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>Information for SIGCSE 2011 Symposium Attendees</h2> </div></div> <p><strong>All conference activities will be at the Sheraton hotel and its attached conference center.</strong> The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <p>A number of room changes have been posted in the online program for workshops and preconference events. Please check the program just before you arrive for updated room assignments.</p> <p><strong>Evaluations:</strong> Please take a few moments to <a href="/sigcse2011/attendees/evaluations.php">fill out the symposium evaluation</a>.</p> <table cellspacing="5px" width="100%"> <tr> <td valign="top" align="left"> <ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> | <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> (<a href="http://docs.google.com/viewer?url=http%3A%2F%2Fwww.sigcse.org%2Fsigcse2011%2Fattendees%2Fdownloads%2Fsigcse2011program.pdf">View Online</a>) | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New for 2011!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions / Dining / Coupons</a> (<em>opens in new window</em>)</li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> </ul> </td> <td nowrap="nowrap" valign="top" align="right"> <div style='width: 240px; height: 420px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/spring1_240x420_bg.jpg ); background-repeat: no-repeat; background-color: #607041;' ><div id='NetweatherContainer' style='height: 405px;' ><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2ex.asp?partner=netweather&tStyle=normal&logo=1&zipcode=75202&lang=eng&size=12&theme=spring1&metric=0&target=_self'></script></div><div style='text-align: center; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 15px; color: #FDEA11;' ><a style='font-size: 10px; color: #FDEA11' href='http://www.accuweather.com/us/TX/DALLAS/75202/city-weather-forecast.asp?partner=accuweather&traveler=0' >Weather Forecast</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/maps-satellite.asp' >Weather Maps</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/index-radar.asp?partner=accuweather&traveler=0&zipcode=75202' >Weather Radar</a></div></div> </td> </tr> </table> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> \ No newline at end of file diff --git a/index.php b/index.php index ac1591c..be78489 100644 --- a/index.php +++ b/index.php @@ -1,89 +1,89 @@ <?php $title = "SIGCSE 2011 - Home"; $menu = "home"; include("parts/top.php"); ?> - +<?php include("parts/today.php"); ?> <div class="SectionHeader"><div class="Full"> <h2>Welcome to SIGCSE 2011</h2> </div></div> <p>SIGCSE 2011 continues our long tradition of bringing together colleagues from around the world to present papers, panels, posters, special sessions, and workshops, and to discuss computer science education in birds-of-a-feather sessions and informal settings at breaks and meals. The SIGCSE Technical Symposium addresses problems common among educators working to develop, implement and/or evaluate computing programs, curricula, and courses. The symposium provides a forum for sharing new ideas for syllabi, laboratories, and other elements of teaching and pedagogy, at all levels of instruction.</p> <p>We encourage participation that addresses our theme, "reaching out". We need to reach out to colleagues in other fields, to develop interdisciplinary courses and research projects that integrate computer science and other fields, which enriches both. We need to reach out to create programs that attract and educate the next generation of computer scientists, especially currently underserved populations. We need to reach out to policy makers, educating them on the importance and promise of our discipline. Finally, we need to reach out to each other, as always sharing our best ideas and experiences with the SIGCSE community. We invite those interested in computer science education and computer science education research to contribute to SIGCSE 2011.</p> <div class="SectionHeader"><div class="Full"> <h2>Our Venue : Sheraton Dallas Hotel</h2> </div></div> <p>All conference activities will be at the Sheraton hotel and its attached conference center. The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <div class="SectionHeader"><div class="Full"> <h2>SIGCSE 2011 Supporters</h2> </div></div> <table width="100%"> <tr> <td align="center" valign="top" colspan="5"><h3>Platinum Plus Supporter</h3></td> </tr> <tr> <td>&nbsp;</td> <?php include("parts/sponsor_microsoft.php"); ?> <td>&nbsp;</td> </tr> <tr> <td align="center" valign="top" colspan="5"><h3>Platinum Supporters</h3></td> </tr> <tr> <td>&nbsp;</td> <?php $sponsors = array("parts/sponsor_google.php", "parts/sponsor_intel.php"); shuffle($sponsors); $doEcho = true; foreach ($sponsors as $sponsor) { include($sponsor); if ($doEcho) { echo "<td>&nbsp;</td>"; $doEcho = false; } } ?> <td>&nbsp;</td> </tr> <tr> <td align="center" valign="top" colspan="5"><h3>Gold Supporters</h3></td> </tr> <tr> <td>&nbsp;</td> <?php $sponsors = array("parts/sponsor_amazon.php", "parts/sponsor_ibm.php"); shuffle($sponsors); $doEcho = true; foreach ($sponsors as $sponsor) { include($sponsor); if ($doEcho) { echo "<td>&nbsp;</td>"; $doEcho = false; } } ?> <td>&nbsp;</td> </tr> </table> <?php include("parts/middle.php"); ?> <?php include("parts/main_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); $mainPage = true; include("parts/footer.php"); ?> \ No newline at end of file diff --git a/parts/today.php b/parts/today.php new file mode 100644 index 0000000..ad6eb5f --- /dev/null +++ b/parts/today.php @@ -0,0 +1,9 @@ +<div class="GoodMessage"> +<p><strong>Thursday March 10th at SIGCSE 2011</strong><br/><ul> +<li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/programAtAGlance.asp?dateRequested=Thursday">Thursday's full program</a></li> +<li>Keynote: Matthias Felleisen, 8:30am. <a href="/sigcse2011/attendees/keynotes.php#thursday">TeachScheme!</a> in Dallas BC</li> +<li>Paper sessions start at 10:45am today</li> +<li>First timers lunch, 12pm in Lone Star A1</li> +<li>Find your way around with <a href="/sigcse2011/attendees/floor_plans.php">floor plans</a></li> +</ul></p> +</div> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
fa12c422f739c0ebe3c7451a6956de6fa4a447fb
correct days for nsf showcases
diff --git a/attendees/nsf_showcase.php b/attendees/nsf_showcase.php index f9e7563..a2e82ec 100644 --- a/attendees/nsf_showcase.php +++ b/attendees/nsf_showcase.php @@ -1,75 +1,75 @@ <?php $title = "SIGCSE 2011 - NSF Showcase"; $menu = "attendees"; include("../parts/top.php"); ?> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>National Science Foundation Showcase</h2> </div></div> <p>All NSF showcases take place in <em>Lone Star BC</em></p> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h3><a name="1">NSF Showcase #1 - Thursday 10:00 - 11:30am</a></h3> </div></div> <p><strong>Location:</strong> Lone Star BC</p> <ul> <li>Problets and Codelets for Learning Introductory Programming (CCLI/TUES): Amruth Kumar</li> <li>"Hands-On" Collaborative Reasoning across the Curriculum (CCLI/TUES): Jason O. Hallstrom, Joseph E. Hollingsworth, Joan Krone, Chong Pak, Murali Sitaraman</li> <li>A Creative Collaboration between CSE and Biological Sciences through Cloud-enabled Evolutionary Biology Learning Tool (CI-TEAM): Bina Ramamurthy, Jessica Poulin, Katharina Dittmar De la Cruz</li> <li>Supporting American's Veterans and Wounded Warriors (CI-TEAM): Ray Vaughn, David Dampier</li> </ul> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h3><a name="2">NSF Showcase #2 - Thursday 3:00 - 4:30pm</a></h3> </div></div> <p><strong>Location:</strong> Lone Star BC</p> <ul> <li>Project MLeXAI: Machine Learning Experiences in the Undergraduate Curriculum (CCLI/TUES): Ingrid Russell, Zdravko Markov</li> <li>From CSI, an Integrated Exhibit and Web-based Learning Initiative, to TexNET, a Professional Development Network for Museum Professionals (ISE): Charlie Walter</li> <li>A Unifying Paradigm for Dynamic Simulation (CPATH): Richard M. Salter</li> <li>Project: CyberCHEQS: A Service-Oriented Cyberinfrastructure (SOCI) for Thermochemical Data and Computation Services (CI-TEAM): Subrata Bhattacharjee, Christopher Paolini, Kris Stewart, Mary Thomas, Ofodike Ezekoye</li> </ul> <div class="SectionHeader" style="clear:left;"><div class="Full"> -<h3><a name="3">NSF Showcase #3 - Thursday 10:00 - 11:30am</a></h3> +<h3><a name="3">NSF Showcase #3 - Friday 10:00 - 11:30am</a></h3> </div></div> <p><strong>Location:</strong> Lone Star BC</p> <ul> <li>The CyberCIEGE Video Game in Cybersecurity Education (SFS): Cynthia Irvine, Michael Thompson</li> <li>Quahog Cohorts: A Community of Student Scientists (S-STEM): Kathryn Sanders</li> <li>Project EXCE2L (Excellence in Computer Education with Entrepreneurship and Leadership Skills) (CPATH): Wendy Tang, Simona Doboli</li> <li>CI-Facilitators: Accelerating Knowledge Development across the STEM Disciplines (CI-TEAM): Jeffrey Stanton, Elizabeth Liddy, Richard Lankes, Derrick Cogburn, Megan Oakleaf</li> </ul> <div class="SectionHeader" style="clear:left;"><div class="Full"> -<h3><a name="4">NSF Showcase #4 - Thursday 3:00 - 4:30pm</a></h3> +<h3><a name="4">NSF Showcase #4 - Friday 3:00 - 4:30pm</a></h3> </div></div> <p><strong>Location:</strong> Lone Star BC</p> <ul> <li>Computational Art and Creative Coding: Teaching CS1 with Processing (CCLI/TUES): Ira Greenberg, Deepak Kumar, Dianna Xu</li> <li>Presentation of the 2011 AlgoViz Awards (NSDL): Cliff Shaffer</li> <li>Demonstration of Remote Robotic Exploration and Experimentation (CI-TEAM): William Smart, Bruce Maxwell</li> <li>Modular CS1 from the Inside Out (CPATH): Christine Alvarado, Zach Dodds</li> </ul> <div class="SectionHeader" style="clear:left;"><div class="Full"> -<h3><a name="5">NSF Showcase #5 - Thursday 10:00 - 11:30am</a></h3> +<h3><a name="5">NSF Showcase #5 - Saturday 10:00 - 11:30am</a></h3> </div></div> <p><strong>Location:</strong> Lone Star BC</p> <ul> <li>Ensemble: Connecting Computing Educators (NSDL): Peter Brusilovsky, Steve Carpenter, Lillian Cassel, Lois M. L. Delcambre, Steve Edwards, Edward A Fox, Richard Furuta, Daniel Garcia, Gregory Hislop, Haowei Hsieh, Frank Shipman</li> <li>Leveraging Map-based CI Resources for Middle School Earth Science Curriculum (CI-TEAM): Youwen Ouyang</li> <li>Encouraging digital literacy, college readiness and persistence among Native Americans (CI-TEAM): Richard Mosholder</li> <li>Computational Thinking as a Foundation for Interdisciplinary Undergraduate Education (CPATH): Suzanne Westbrook</li> </ul> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?>
mikehelmick/SIGCSE2011-Web-Site
a093a1011af1c4f986708b4b2af7490b0404e969
activate the evaluations page
diff --git a/attendees/evaluations.php b/attendees/evaluations.php index 2576fd4..faa7127 100644 --- a/attendees/evaluations.php +++ b/attendees/evaluations.php @@ -1,23 +1,21 @@ <?php $title = "SIGCSE 2011 - Evaluations"; $menu = "attendees"; include("../parts/top.php"); ?> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>SIGCSE 2011 Symposium Evaluations</h2> </div></div> <p>The SIGCSE 2011 Conference Committee hopes that you enjoyed (or are still enjoying!) this year's symposium. To help us learn what we did well, and what we could have done better, we invite you to complete the Symposium Evaluation survey. These survey results not only inform the 2011 committee, they also provide valuable insight to the members of the SIGCSE 2012 committee.</p> <p>To complete an evaluation on-line, please select one of the following links. <ul> - <li><em>The survey will be available before the conference starts.</em> - <!-- <a href="http://www.surveymonkey.com/s/SIGCSE2011">SIGCSE 2011 Symposium Evaluation</a> --></li> + <li><a href="https://www.surveymonkey.com/s/SIGCSE2011">SIGCSE 2011 Symposium Evaluation</a></li> </ul> </p> -<p>Please be aware: If you are unable or unwilling to complete this survey on-line, paper copies of the surveys are available from the symposium registration desk at the convention center.</p> -<p>Thank you!</p> +<p>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;</p> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> diff --git a/attendees/index.php b/attendees/index.php index f954cd6..0e8d905 100644 --- a/attendees/index.php +++ b/attendees/index.php @@ -1,62 +1,64 @@ <?php $title = "SIGCSE 2011 - Information for Symposium Attendees"; $menu = "attendees"; $submenu = "cfp"; include("../parts/top.php"); ?> <!-- <h2>Important Dates</h2> --> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>Information for SIGCSE 2011 Symposium Attendees</h2> </div></div> <p><strong>All conference activities will be at the Sheraton hotel and its attached conference center.</strong> The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <p>A number of room changes have been posted in the online program for workshops and preconference events. Please check the program just before you arrive for updated room assignments.</p> +<p><strong>Evaluations:</strong> Please take a few moments to <a href="/sigcse2011/attendees/evaluations.php">fill out the symposium evaluation</a>.</p> + <table cellspacing="5px" width="100%"> <tr> <td valign="top" align="left"> <ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> | <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> (<a href="http://docs.google.com/viewer?url=http%3A%2F%2Fwww.sigcse.org%2Fsigcse2011%2Fattendees%2Fdownloads%2Fsigcse2011program.pdf">View Online</a>) | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New for 2011!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions / Dining / Coupons</a> (<em>opens in new window</em>)</li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> </ul> </td> <td nowrap="nowrap" valign="top" align="right"> <div style='width: 240px; height: 420px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/spring1_240x420_bg.jpg ); background-repeat: no-repeat; background-color: #607041;' ><div id='NetweatherContainer' style='height: 405px;' ><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2ex.asp?partner=netweather&tStyle=normal&logo=1&zipcode=75202&lang=eng&size=12&theme=spring1&metric=0&target=_self'></script></div><div style='text-align: center; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 15px; color: #FDEA11;' ><a style='font-size: 10px; color: #FDEA11' href='http://www.accuweather.com/us/TX/DALLAS/75202/city-weather-forecast.asp?partner=accuweather&traveler=0' >Weather Forecast</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/maps-satellite.asp' >Weather Maps</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/index-radar.asp?partner=accuweather&traveler=0&zipcode=75202' >Weather Radar</a></div></div> </td> </tr> </table> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
f27470c88c153847b231d673f1521ef5ec2fd901
corrected program
diff --git a/attendees/downloads/sigcse2011program.pdf b/attendees/downloads/sigcse2011program.pdf index 6624c76..264f8fa 100644 Binary files a/attendees/downloads/sigcse2011program.pdf and b/attendees/downloads/sigcse2011program.pdf differ
mikehelmick/SIGCSE2011-Web-Site
c83c44b286d8caafbe67025af31884acd9480da9
add gview link for program
diff --git a/attendees/index.php b/attendees/index.php index 66306cd..f954cd6 100644 --- a/attendees/index.php +++ b/attendees/index.php @@ -1,62 +1,62 @@ <?php $title = "SIGCSE 2011 - Information for Symposium Attendees"; $menu = "attendees"; $submenu = "cfp"; include("../parts/top.php"); ?> <!-- <h2>Important Dates</h2> --> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>Information for SIGCSE 2011 Symposium Attendees</h2> </div></div> <p><strong>All conference activities will be at the Sheraton hotel and its attached conference center.</strong> The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <p>A number of room changes have been posted in the online program for workshops and preconference events. Please check the program just before you arrive for updated room assignments.</p> <table cellspacing="5px" width="100%"> <tr> <td valign="top" align="left"> <ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> - | <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> + | <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> (<a href="http://docs.google.com/viewer?url=http%3A%2F%2Fwww.sigcse.org%2Fsigcse2011%2Fattendees%2Fdownloads%2Fsigcse2011program.pdf">View Online</a>) | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New for 2011!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions / Dining / Coupons</a> (<em>opens in new window</em>)</li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> </ul> </td> <td nowrap="nowrap" valign="top" align="right"> <div style='width: 240px; height: 420px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/spring1_240x420_bg.jpg ); background-repeat: no-repeat; background-color: #607041;' ><div id='NetweatherContainer' style='height: 405px;' ><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2ex.asp?partner=netweather&tStyle=normal&logo=1&zipcode=75202&lang=eng&size=12&theme=spring1&metric=0&target=_self'></script></div><div style='text-align: center; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 15px; color: #FDEA11;' ><a style='font-size: 10px; color: #FDEA11' href='http://www.accuweather.com/us/TX/DALLAS/75202/city-weather-forecast.asp?partner=accuweather&traveler=0' >Weather Forecast</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/maps-satellite.asp' >Weather Maps</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/index-radar.asp?partner=accuweather&traveler=0&zipcode=75202' >Weather Radar</a></div></div> </td> </tr> </table> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
b06bdd91f284002fc0797f96f76d5737ab3a52f3
add pdf program
diff --git a/attendees/downloads/sigcse2011program.pdf b/attendees/downloads/sigcse2011program.pdf new file mode 100644 index 0000000..6624c76 Binary files /dev/null and b/attendees/downloads/sigcse2011program.pdf differ diff --git a/attendees/index.php b/attendees/index.php index 87fe1d4..66306cd 100644 --- a/attendees/index.php +++ b/attendees/index.php @@ -1,69 +1,62 @@ <?php $title = "SIGCSE 2011 - Information for Symposium Attendees"; $menu = "attendees"; $submenu = "cfp"; include("../parts/top.php"); ?> <!-- <h2>Important Dates</h2> --> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>Information for SIGCSE 2011 Symposium Attendees</h2> </div></div> <p><strong>All conference activities will be at the Sheraton hotel and its attached conference center.</strong> The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <p>A number of room changes have been posted in the online program for workshops and preconference events. Please check the program just before you arrive for updated room assignments.</p> <table cellspacing="5px" width="100%"> <tr> <td valign="top" align="left"> <ul> - <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> | - <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> + <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> + | <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> + | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New for 2011!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions / Dining / Coupons</a> (<em>opens in new window</em>)</li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> - - <!-- - <li><a href="/sigcse2011/attendees/reception.php"><img src="/sigcse2011/images/cake.png" align="absmiddle"/> Reception</a></li> - <li><a href="/sigcse2011/attendees/special_projects.php"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE Special Projects</a></li> - <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> - <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> - - --> </ul> </td> <td nowrap="nowrap" valign="top" align="right"> <div style='width: 240px; height: 420px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/spring1_240x420_bg.jpg ); background-repeat: no-repeat; background-color: #607041;' ><div id='NetweatherContainer' style='height: 405px;' ><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2ex.asp?partner=netweather&tStyle=normal&logo=1&zipcode=75202&lang=eng&size=12&theme=spring1&metric=0&target=_self'></script></div><div style='text-align: center; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 15px; color: #FDEA11;' ><a style='font-size: 10px; color: #FDEA11' href='http://www.accuweather.com/us/TX/DALLAS/75202/city-weather-forecast.asp?partner=accuweather&traveler=0' >Weather Forecast</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/maps-satellite.asp' >Weather Maps</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/index-radar.asp?partner=accuweather&traveler=0&zipcode=75202' >Weather Radar</a></div></div> </td> </tr> </table> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> \ No newline at end of file diff --git a/parts/attendees_right.php b/parts/attendees_right.php index c9bb1bb..3e55b62 100644 --- a/parts/attendees_right.php +++ b/parts/attendees_right.php @@ -1,25 +1,26 @@ <ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> | + <a href="/sigcse2011/attendees/downloads/sigcse2011program.pdf">Download Program PDF</a> | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions</a></li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> </ul> \ No newline at end of file
mikehelmick/SIGCSE2011-Web-Site
477fb07be6f660476737053b22770595c9a2492c
mark registration as closed
diff --git a/attendees/index.php b/attendees/index.php index ba822c7..87fe1d4 100644 --- a/attendees/index.php +++ b/attendees/index.php @@ -1,69 +1,69 @@ <?php $title = "SIGCSE 2011 - Information for Symposium Attendees"; $menu = "attendees"; $submenu = "cfp"; include("../parts/top.php"); ?> <!-- <h2>Important Dates</h2> --> <div class="SectionHeader" style="clear:left;"><div class="Full"> <h2>Information for SIGCSE 2011 Symposium Attendees</h2> </div></div> <p><strong>All conference activities will be at the Sheraton hotel and its attached conference center.</strong> The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <p>A number of room changes have been posted in the online program for workshops and preconference events. Please check the program just before you arrive for updated room assignments.</p> <table cellspacing="5px" width="100%"> <tr> <td valign="top" align="left"> <ul> <li><a href="http://db.grinnell.edu/sigcse/sigcse2011/Program/Program.asp"><img src="/sigcse2011/images/report.png" align="absmiddle" /> Symposium Program</a> | <a href="/sigcse2011/attendees/calendar.php">Calendar</a></li> <li><a href="/sigcse2011/attendees/keynotes.php"><img src="/sigcse2011/images/user_suit.png" align="absmiddle" /> Keynote Speakers</a></li> <li><a href="/sigcse2011/attendees/supporter_sessions.php"><img src="/sigcse2011/images/building.png" align="absmiddle"/> Supporter Sessions</a></li> <li><a href="/sigcse2011/attendees/pre_symposium_events.php"><img src="/sigcse2011/images/calendar.png" align="absmiddle"/> Pre-Symposium Events</a></li> <li><a href="/sigcse2011/attendees/nsf_showcase.php"><img src="/sigcse2011/images/images.png" align="absmiddle"/> NSF Showcase</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE 2011 Robot Hoedown and Rodeo</a> <strong>New for 2011!</strong> <ul><li><a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">Call for Wranglers</a></li></ul> </li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> <li><a href="/sigcse2011/attendees/student_research.php"><img src="/sigcse2011/images/award_star_gold_3.png" align="absmiddle"/> Student Research Competition</a></li> - <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <strong>NOW OPEN!</strong> + <li><a href="/sigcse2011/attendees/registration.php"><img src="/sigcse2011/images/vcard_add.png" align="absmiddle"/> Registration</a> <ul><li><a href="/sigcse2011/attendees/fees.php"><img src="/sigcse2011/images/money.png" align="absmiddle"/> A Sneak Peak at Fees</a></li></ul> </li> <li><a href="/sigcse2011/attendees/pokens.php"><img src="/sigcse2011/images/vcard.png" align="absmiddle"> Pokens: A new way to connect at SIGCSE 2011</a></li> <li><a href="/sigcse2011/attendees/travel_information.php"><img src="/sigcse2011/images/tag_orange.png" align="absmiddle"/> Travel Information</a></li> <li><a href="/sigcse2011/attendees/accommodations.php"><img src="/sigcse2011/images/clock.png" align="absmiddle"/> Accommodations</a></li> - <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions</a> (<em>opens in new window</em>)</li> + <li><a href="http://www.visitdallas.com/WelcomeSIGCSE2011" target="_blank"><img src="/sigcse2011/images/weather_sun.png" align="absmiddle"/> Local Attractions / Dining / Coupons</a> (<em>opens in new window</em>)</li> <li><a href="/sigcse2011/attendees/kids_camp.php"><img src="/sigcse2011/images/group.png" align="absmiddle"/> Kids Camp</a></li> <li><a href="/sigcse2011/attendees/visas.php"><img src="/sigcse2011/images/folder_database.png" align="absmiddle"/> Visa Information</a></li> <li><a href="/sigcse2011/attendees/floor_plans.php"><img src="/sigcse2011/images/map.png" align="absmiddle"/> Floor Plans</a></li> <li><a href="/sigcse2011/faq/#attendees"><img src="/sigcse2011/images/help.png" align="absmiddle" /> FAQ</a></li> <!-- <li><a href="/sigcse2011/attendees/reception.php"><img src="/sigcse2011/images/cake.png" align="absmiddle"/> Reception</a></li> <li><a href="/sigcse2011/attendees/special_projects.php"><img src="/sigcse2011/images/bricks.png" align="absmiddle"/> SIGCSE Special Projects</a></li> <li><a href="/sigcse2011/attendees/video_program.php"><img src="/sigcse2011/images/television.png" align="absmiddle"/> Video Program</a></li> <li><a href="/sigcse2011/attendees/k12_highlights.php"><img src="/sigcse2011/images/house.png" align="absmiddle"/> Highlights for K-12 Teachers</a></li> --> </ul> </td> <td nowrap="nowrap" valign="top" align="right"> <div style='width: 240px; height: 420px; background-image: url( http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/spring1_240x420_bg.jpg ); background-repeat: no-repeat; background-color: #607041;' ><div id='NetweatherContainer' style='height: 405px;' ><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2ex.asp?partner=netweather&tStyle=normal&logo=1&zipcode=75202&lang=eng&size=12&theme=spring1&metric=0&target=_self'></script></div><div style='text-align: center; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 15px; color: #FDEA11;' ><a style='font-size: 10px; color: #FDEA11' href='http://www.accuweather.com/us/TX/DALLAS/75202/city-weather-forecast.asp?partner=accuweather&traveler=0' >Weather Forecast</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/maps-satellite.asp' >Weather Maps</a> | <a style='color: #FDEA11' href='http://www.accuweather.com/index-radar.asp?partner=accuweather&traveler=0&zipcode=75202' >Weather Radar</a></div></div> </td> </tr> </table> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> \ No newline at end of file diff --git a/attendees/registration.php b/attendees/registration.php index 3e917f1..c8bbe45 100644 --- a/attendees/registration.php +++ b/attendees/registration.php @@ -1,60 +1,50 @@ <?php $title = "SIGCSE 2011 - Registration"; $menu = "attendees"; include("../parts/top.php"); ?> -<div id="GoodMessage"><strong>Online registration is open, and will remain open through Thursday, March 3.</strong></div> <h1>SIGCSE 2011 Registration Gateway</h1> +<div class="errorExplanation">Pre-registration is now closed. You can still register in person at SIGCSE 2011 in Dallas.</div> <div class="SectionHeader"><div class="Full"> <h2>Registration</h2> </div></div> <br/> <p>As with past SIGCSE symposia, we are offering attendees three registration options: On-line, off-line, and on-site. Early registration for SIGCSE members is just $235 for registrations made by January 31, 2011. Details about late registration and many other symposium activity fees are available from our Symposium Fees page.</p> <p><b>Parents</b>: Interested in bringing your kids to SIGCSE? We will continue the tradition of "Kids' Camp" for fun and educational child care during SIGCSE.</p> <p><strong>WIN A FREE UPGRADE</strong>: Every attendee that preregisters for SIGCSE 2011 at the regular conference rate and <a href="accommodations.php">reserves a room at the Sheraton Dallas</a> will be entered into a drawing to win a complimentary upgrade to a suite. (Free upgrade drawing not available with exhibits-only, teacher or student rates.)</p> <div class="SectionHeader"><div class="Full"> <h2>Online and Offline (Remote) Registration</h2> </div></div><br/> - -<div class="errorExplanation">In order to register for two half-day <a href="pre_symposium_events.php">pre-symposium events</a> (Wednesday), you must select the combination of the two events that you wish to addend, rather then select the two events individually.</div> - -<ul> - <li><a href="http://www.regonline.com/sigcse2011">Online Registration</a> via regonline.com</li> - <li>Register by Mail</li> - <ul> - <li><img src="/sigcse2011/images/page_white_acrobat.png" /><a href="/sigcse2011/downloads/RegistrationForm.pdf">Registration Form (PDF)</a></li> - <li><img src="/sigcse2011/images/page_white_word.png" /><a href="/sigcse2011/downloads/RegistrationForm.docx">Registration Form (Microsoft Word - docx format)</a></li> - </ul> -</ul> +<div class="errorExplanation">Pre-registration is now closed.</div> <div class="SectionHeader"><div class="Full"> <h2>On-Site Registration</h2> </div></div><br/> <p>Onsite registration will be open the following times: <ul><li>Wed - 3:00 PM - 9:30 PM</li> <li>Thu - 7:30 AM - 4:00 PM</li> <li>Fri - 7:30 AM - 5:00 PM</li> <li>Sat - 8:00 AM - 12:15 PM and 2:30 PM - 3:00 PM</li> </ul> </p> <br/> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?> diff --git a/index.php b/index.php index f7c9379..ac1591c 100644 --- a/index.php +++ b/index.php @@ -1,89 +1,89 @@ <?php $title = "SIGCSE 2011 - Home"; $menu = "home"; include("parts/top.php"); ?> -<div id="GoodMessage"><strong><a href="/sigcse2011/attendees/registration.php">Online registration is now open</a>! <em>Online registration is only through Thursday, March 3.</em></strong></div> + <div class="SectionHeader"><div class="Full"> <h2>Welcome to SIGCSE 2011</h2> </div></div> <p>SIGCSE 2011 continues our long tradition of bringing together colleagues from around the world to present papers, panels, posters, special sessions, and workshops, and to discuss computer science education in birds-of-a-feather sessions and informal settings at breaks and meals. The SIGCSE Technical Symposium addresses problems common among educators working to develop, implement and/or evaluate computing programs, curricula, and courses. The symposium provides a forum for sharing new ideas for syllabi, laboratories, and other elements of teaching and pedagogy, at all levels of instruction.</p> <p>We encourage participation that addresses our theme, "reaching out". We need to reach out to colleagues in other fields, to develop interdisciplinary courses and research projects that integrate computer science and other fields, which enriches both. We need to reach out to create programs that attract and educate the next generation of computer scientists, especially currently underserved populations. We need to reach out to policy makers, educating them on the importance and promise of our discipline. Finally, we need to reach out to each other, as always sharing our best ideas and experiences with the SIGCSE community. We invite those interested in computer science education and computer science education research to contribute to SIGCSE 2011.</p> <div class="SectionHeader"><div class="Full"> <h2>Our Venue : Sheraton Dallas Hotel</h2> </div></div> <p>All conference activities will be at the Sheraton hotel and its attached conference center. The Sheraton Dallas Hotel and conference center is located at 400 North Olive Street, Dallas, TX 75201. More information can be found on our <a href="/sigcse2011/attendees/accommodations.php">accommodations page</a>.</p> <div class="SectionHeader"><div class="Full"> <h2>SIGCSE 2011 Supporters</h2> </div></div> <table width="100%"> <tr> <td align="center" valign="top" colspan="5"><h3>Platinum Plus Supporter</h3></td> </tr> <tr> <td>&nbsp;</td> <?php include("parts/sponsor_microsoft.php"); ?> <td>&nbsp;</td> </tr> <tr> <td align="center" valign="top" colspan="5"><h3>Platinum Supporters</h3></td> </tr> <tr> <td>&nbsp;</td> <?php $sponsors = array("parts/sponsor_google.php", "parts/sponsor_intel.php"); shuffle($sponsors); $doEcho = true; foreach ($sponsors as $sponsor) { include($sponsor); if ($doEcho) { echo "<td>&nbsp;</td>"; $doEcho = false; } } ?> <td>&nbsp;</td> </tr> <tr> <td align="center" valign="top" colspan="5"><h3>Gold Supporters</h3></td> </tr> <tr> <td>&nbsp;</td> <?php $sponsors = array("parts/sponsor_amazon.php", "parts/sponsor_ibm.php"); shuffle($sponsors); $doEcho = true; foreach ($sponsors as $sponsor) { include($sponsor); if ($doEcho) { echo "<td>&nbsp;</td>"; $doEcho = false; } } ?> <td>&nbsp;</td> </tr> </table> <?php include("parts/middle.php"); ?> <?php include("parts/main_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); $mainPage = true; include("parts/footer.php"); ?> \ No newline at end of file diff --git a/parts/main_right.php b/parts/main_right.php index 4edebbf..db9f446 100644 --- a/parts/main_right.php +++ b/parts/main_right.php @@ -1,16 +1,14 @@ <h2>News</h2> <ul> <li>The following workshops have been canceled: #25, #28, #31, #32, #34.</li> - <li><a href="/sigcse2011/attendees/registration.php">Online registration is now open.</a></li> - <li>New event for 2011! <a href="http://elvis.rowan.edu/~kay/sigcse/rodeo.html">Robot Hoedown and Rodeo</a>. No experience necessary, but if you have robots and experience, <a href="http://elvis.rowan.edu/~kay/sigcse/cfw.html">we could use you as a wrangler</a>!</li> </ul> <h2>Connect</h2> <ul> <li>Twitter: <a href="http://twitter.com/sigcse2011">twitter.com/sigcse2011</a> <ul><li>Tag your tweets with <code>#sigcse</code></li></ul> </li> <li>Facebook: <a href="http://www.facebook.com/group.php?gid=373261951323">SIGCSE 2011 Group</a></li> <li>Flickr: <a href="http://www.flickr.com/groups/sigcse2011/">Share your photos!</a></li> </ul>
mikehelmick/SIGCSE2011-Web-Site
b7636beae76f48e693ac5f24d12eb2a7a0978a5a
mark ethics event as full
diff --git a/attendees/pre_symposium_events.php b/attendees/pre_symposium_events.php index 3852c23..4e180fa 100644 --- a/attendees/pre_symposium_events.php +++ b/attendees/pre_symposium_events.php @@ -1,212 +1,213 @@ <?php $title = "SIGCSE 2011 - Pre-Symposium Events"; $menu = "attendees"; include("../parts/top.php"); ?> <h1>SIGCSE 2011 Pre-Symposium Events</h1> <div class="SectionHeader"><div class="Full"> <h2><a name="csta">CSTA Source Web Repository Cataloging Workshop</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am to 3:30pm. <p>Chris Stephenson, CSTA Executive Director</p> <p>Participants will learn how to appropriately review and classify resources submitted for entry in to the Source Web Repository.</p> <p>Contact: Christina San Filippo <script>write_email("sanfilippo", "hq.acm.org");</script></p> <div class="SectionHeader"><div class="Full"> <h2><a name="department_chairs">Department Chairs' Pre-Symposium Workshop</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am to 5:30pm. <p>The Pre-Symposium Workshop for Department Chairs is an opportunity for all department chairs (experienced and inexperienced) to improve their understanding of their duties and their ability to perform them. Participants should also include those interested in becoming department chairs. Four experienced former department chairs will serve as resources for the group as the participants review and discuss the duties of the department chair and explore ways that chairs can do their jobs efficiently and effectively. Some specific discussion topics will include leadership styles, time management, legal issues, academic program assessment, and faculty promotion and tenure. </p> <div class="SectionHeader"><div class="Full"> <h2><a name="hawaii">Hawaii - Project companion for cloud-enabled mobile computing courses</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 1:00pm - 5:00pm <p>Microsoft Research's Project Hawaii is an academic outreach and research dissemination project. The academic goal of Hawaii is to enable graduate and undergraduate university students to gain understanding and expertise in developing cloud-enabled mobile applications using the Microsoft Mobile and Cloud infrastructure. Project Hawaii is a collection of cloud services, hosted in Windows Azure; a Visual Studio 2010 based development SDK and sample application code; a community forum for exchange of ideas; and, mobile platform hardware (Windows Phone 7). Project Hawaii started in Spring 2010 when it was offered as a pilot project in USC, Duke and Wisconsin-Madison. In Fall 2010 Project Hawaii was offered in MSU, CMU, Michigan, Maryland, Arkansas, UCSB and Singapore Management U. Its third offering would be in Spring 2011 in more than 15 schools internationally. Prominent among the Spring 2011 schools are Stanford, UCSB, Purdue, University College London; to name a few.</p> <p>In this session Project Hawaii team will provide an overview of the project, with an emphasis on its use as a project companion for teaching mobile and cloud computing courses. Instructors who have been associated with Project Hawaii will be invited to talk about their experiences using Hawaii as a course companion for teaching cloud-enabled mobile computing courses to graduate and undergraduate computer science and engineering students. Demonstrations of projects by students using Hawaii will be featured in the demo session.</p> <div class="SectionHeader"><div class="Full"> <h2><a name="innovativeApproaches">Innovative approaches to introducing Computer Science</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 11:00am - 5:30pm <p>This pre-conference workshop will bring together faculty to discuss innovative approaches to introducing computer science using novel problem domains. The innovation may be primarily through pedagogy. For example, an instructor may use problem-based learning to build a course around real, domain-specific problems and the techniques necessary to solve them, rather than addressing a list of topics. Alternatively, a novel approach may address a new context such as the modeling and analysis of social networks. The workshop will address approaches that seek to change the culture and practice of computer science by addressing the pipeline at its early stages, specifically in introductory college courses in computer science, mathematics, statistics, and the social and natural sciences.</p> <p>More information at <a href="http://harambeenet.org/sigcse11">http://harambeenet.org/sigcse11</a></p> <p>Organizers and affiliations: <ul> <li>Jeff Forbes, Duke University - <script>write_email("jforbes", "duke.edu");</script></li> <li>Owen Astrachan, Duke University - <script>write_email("ola", "cs.duke.edu");</script></li> </ul> </p> <div class="SectionHeader"><div class="Full"> <h2><a name="womenFaculty">Managing the Academic Career for Women Faculty in Undergraduate Computing Programs</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am - 5:30pm <p>Women in Computer Science and Engineering (CSE) face particular challenges in pursuing and maintaining academic careers at primarily undergraduate academic institutions. Women academicians in CSE typically have few female colleagues to provide critical information about the culture and content required for successful academic careers. To help this situation, the Computing Research Association Committee on the Status of Women in Computing Research (CRA-W) will sponsor a career/mentoring workshop titled "Managing the Academic Career for Women Faculty in Undergraduate Computing Programs". The day-long workshop, to be held on Wednesday, March 9, will be co-located with the SIGCSE 2011 conference in Dallas. The goal of the workshop is to provide critical mentoring information for women at all career levels in undergraduate teaching. The target audiences of the workshop are pre-tenure faculty and graduate students in Computer Science and Engineering who are interested in an academic career, as well as post-tenure (senior) faculty seeking to improve their teaching and mentoring skills.</p> <p>More information at <a href="http://cra-w.org/ArticleDetails/tabid/77/ArticleID/75/Default.aspx">http://cra-w.org/ArticleDetails/tabid/77/ArticleID/75/Default.aspx</a></p> <p> <ul> <li>Susan Rodger, Duke University - <script>write_email("rodger", "cs.duke.edu");</script></li> <li>Sheila Castaneda, Clarke University - <script>write_email("Sheila.Castaneda", "clarke.edu");</script></li> </ul> </p> <div class="SectionHeader"><div class="Full"> <h2><a name="new_faculty">New Educators Roundtable</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 1:00pm - 5:30pm <p><em>When registering, this event is available as a single choice or as a combo with another half-day event.</em></p> <p>New to teaching? Seeking advice and mentorship? Join us at the New Educators Roundtable (NER), a half-day workshop designed to mentor college and university faculty who are new to teaching. We welcome participants from across the entire teaching spectrum: tenure-track faculty at institutions where teaching is central, teaching-track faculty and lecturers, and graduate students who currently teach or are looking forward to an academic career. Come with your questions and concerns, learn from the experiences and best practices of sage elders, and build an international support group for your career.</p> <p>More information at <a href="http://dave-reed.com/NER">http://dave-reed.com/NER</a></p> <p><ul> <li>Julie Zelenski, Stanford University</li> <li>David Reed, Creighton University</li> </ul></p> <div class="SectionHeader"><div class="Full"> <h2><a name="sigcas">Open meeting of the Special Interest Group on Computers and Society (SIGCAS)</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am - 12:00pm <p><em>When registering, this event is available as a single choice or as a combo with another half-day event.</em></p> <p>This open meeting of ACM's Special Interest Group on Computers and Society (SIGCAS) is an opportunity for SIGCAS members and supporters to provide input into the future direction of the SIG. Particular attention will be paid to issues of interest to SIGCAS members who are primarily computer science educators.</p> <p>Organizers and affiliations: SIGCAS, Florence Appel, Saint Xavier University</p> <div class="SectionHeader"><div class="Full"> <h2><a name="programByDesign">Program by Design: Bootstrap, TeachScheme, ReachJava, and Beyond</a></h2> </div></div> <div class="errorExplanation">This event is full.</div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am to 5:30pm <p>More information at <a href="http://www.programbydesign.org/events/sigcse2011">http://www.programbydesign.org/events/sigcse2011</a></p> <p>Want to create excitement without sacrificing principles or losing a clear connection to mainstream CS? Check out Program by Design, which is what TeachScheme! has grown up to become. See how you can program animations, the Web, and mobile phone apps from week 1; learn about the smooth transition to Java; and acquaint yourself with the middle-school component, used in inner-city after-school programs nationwide. This one-day workshop gives a detailed overview of the high-school/college curriculum, including the path to Java. A late-afternoon session includes demos of different assignments, discussion of the middle-school program, and a chance to interact with current users of the curriculum.</p> <p>Contact: Viera Proulx, <script>write_email("vkp", "ccs.neu.edu");</script></p> <div class="SectionHeader"><div class="Full"> <h2><a name="alice2.2">Programming with Alice Workshop (Alice 2.2)</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am - 5:30pm <p>This workshop is intended for teachers who have little or no experience in teaching with Alice. The workshop will provide hands-on experience with learning to use Alice 2.2 and in learning to teach with Alice. Alice 2.2 is a powerful program visualization environment where students are engaged in building virtual worlds to create animations and simple games. Instructional materials, software, and a complimentary copy of the 3rd edition of the text, <em>Learning to Program with Alice</em>, will be provided to each participant.</p> <p>More information at <a href="http://www.andrew.cmu.edu/user/wpdann/workshops.html">http://www.andrew.cmu.edu/user/wpdann/workshops.html</a></p> <p>Contact: Wanda Dann, Carnegie-Mellon University<br/> <script>write_email("wpdann", "andrew.cmu.edu");</script> <div class="SectionHeader"><div class="Full"> <h2><a name="alice3">Programming with Alice Workshop (Alice 3)</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am - 5:30pm <p>This workshop is designed for instructors of CS1/AP who are interested in providing a gentle introduction to programming concepts in Alice 3 integral with mediating the transfer of these concepts into Java. The workshop will introduce Alice 3 and a plugin for transitioning from Alice to Java. Alice 3 builds on Alice 2's powerful program visualization technique, enabling students to "see" objects and work with object-oriented programming. Participants will learn how to use Alice 3 to build virtual worlds and how to use this approach in CS1 courses (introductory programming for majors and non-majors and AP CS).</p> <p>More information at <a href="http://www.andrew.cmu.edu/user/wpdann/workshops.html">http://www.andrew.cmu.edu/user/wpdann/workshops.html</a></p> <p>Contact: Wanda Dann, Carnegie-Mellon University<br/> <script>write_email("wpdann", "andrew.cmu.edu");</script> <div class="SectionHeader"><div class="Full"> <h2><a name="ethics">Teaching Professional Ethics in Computer Science: Tips and Traps</a></h2> </div></div> +<div class="errorExplanation">This event is full.</div> <p><em>When registering, this event is available as a single choice or as a combo with another half-day event.</em></p> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 1:15pm to 5:30pm <p>In support of ACM's Commitment to Ethical Professionalism this event is designed to help interested faculty provide students with tools to better understand and resolve the ethical challenges in their professional lives we will present well developed examples and modules which can be used to engage students in the study of applied ethics. We will present materials to be used in a complete computer ethics course and that can be used as examples and exercises in specific technical courses; including case studies, suggested course syllabi, and suggestions for creating and grading assignments.</p> <p>More information at <a href="https://edocs.uis.edu/kmill2/www/sigcse2011computerEthics.html">https://edocs.uis.edu/kmill2/www/sigcse2011computerEthics.html</a></p> <p>Organizers and affiliations: <ul> <li>Bo Brinkman, Miami University (Ohio)</li> <li>Don Gotterbarn, East Tennessee State University - <script>write_email("don", "gotterbarn.com");</script></li> <li>Keith Miller, University of Illinois Springfield</li> </ul> <div class="SectionHeader"><div class="Full"> <h2><a name="hfoss">The 3rd Annual Humanitarian FOSS Symposium 2011</a></h2> </div></div> <img src="/sigcse2011/images/clock.png" align="absmiddle" />Wednesday, March 9, 2011, 8:00am - 5:30pm <p>The Third annual HFOSS Education Symposium (<a href="http://www.hfoss.org/hfoss2011">HFOSS 2011</a>), held as a SIGCSE 2011 pre-conference activity (March 9th 2011, Dallas, Texas), aims to bring together educators, software developers, industry representatives, and students to continue the discussion of how best to promote HFOSS within undergraduate computing education. Humanitarian FOSS is free and open source software that contributes in some way to the public good. This year's symposium focuses on applying HFOSS within the local community -- i.e., in local government, in K-12 education, and in collaboration with local non-profit organizations. This years keynote speaker is Bryan Sivak, Chief Technology Officer for the District of Columbia, founding member and advisory board member of Civic Commons. As in previous years, the symposium will be highly interactive, taking place entirely in plenary sessions. In addition to the keynote address by Bryan Sivak, the symposium will include a poster session, and panels on government, K-12 education, and non-profits, made up of invited speakers and participants from industry, academia, and the non-profit sector.</p> <p>For more information and registration visit <a href="http://www.hfoss.org/hfoss2011">http://www.hfoss.org/hfoss2011</a></p> <p>Organizers and affiliations: <ul> <li>Ralph Morelli (chair), Trinity College</li> <li>Trishan de Lanerolle, Trinity College</li> <li>Danny Krizanc, Wesleyan University</li> <li>Norman Danner, Wesleyan University</li> <li>Gary Parker, Connecticut College</li> <li>Ozgur Izmirli, Connecticut College</li> <li>Carlos Espinosa, Trinity College</li> <li>Allen Tucker, Bowdoin College </li> </ul> </p> <br/> <?php include("../parts/middle.php"); ?> <?php include("../parts/attendees_right.php"); ?> <?php $updated = filemtime( $_SERVER["SCRIPT_FILENAME"] ); include("../parts/footer.php"); ?>