Newbie Needs Direction - Monitor contents of variable in a seperate process - c++

I want to apologize up front for being unfamiliar with the terminology I should use. I have programming experience, but not in this area. I'm looking for general guidance, links to helpful sources, books, ect that will help me understand my problem better and can possible give a tutorial on how to achieve a solution.
On the surface, I think what I am trying to do is pretty simple, it's just I have never done any programming with hooking other applications.
The Goal:
I am trying to monitor (not change) a variable (or a few variables) in a game. In the UI of the game, there is a box that lists some items in plain text. I want to know what items that box contains. I would like a function in my code that returns the contents of that box as a string. This could be done with OCR, but I was thinking this may be a better, faster, more accurate solution. Plus, OCR isn't a simple solution either.
I will likely be writing my program in C++, since it seems like that would be the best language for my overall project (of which, this is just a small, but important part).
I would appreciate your thoughts or suggestions on the best way to achieve this. Especially any references that may help me to create such a function.
Thank you.

One approach is to have a "monitoring" task that goes through the variables and sends events to a container of recipients. The frequency would be adjustable via sleep command.
You could also use an std::bitset to indicate whether the variable's value has changed since the last notification and only notify recipients of the changed variables.
Research "subscriber design pattern" and "publisher design pattern".

Related

How to select the right architectural/design patterns

I am doing my own research project, and I am quite struggling regarding the right choice of architectural/design patterns.
In this project, after the "system" start, I need to do something in background (tasks, processing, display data and so on) and at the same be able to interact with the system using, for example, keyboard and send some commands, like "give me status of this particular object" or "what is the data in this object".
So my question is - what software architectural/design patterns can be applied to this particular project? How the interraction between classes/objects should be organized? How should the objects be created?
Can, for example, "event-driven architecture" or "Microkernel" be applied here? Some references to useful resources will be very much appreciated!
Thank you very much in advance!
Careful with design patterns. If you sprinkle them throughout your code hoping that everything will work great, you'll soon have an unreadable, boilerplate full mess. They are recipes, not solutions.
My advice to you is pick a piece of paper and a pencil and start drawing all the entities of your domain, with all their requisites, and see how they relate. If you want to get somewhat serious about it, you can do something like this.
When defining your entities, strive for high cohesion and loose coupling.
High cohesion means that you should keep similar functionalities together. In a very simple example, if you have a class that reads stuff from a file and processes it, the class has low cohesion, since reading and processing are two very distinct functionalities. In this case, you would want a class for each functionality.
As for loose coupling, it means that your entities should be independent of each other. Using the example above, supposed that you are now the proud owner of two highly cohesive classes - one that reads stuff from a file (Reader), and one that processes that stuff (Processor). Now, suppose that the Processor class has an instance of the Reader class, and calls it in order to get its input. In this case, we can say that both classes are tightly coupled, since Processor won't work without Reader. In the OOP world, the solution for this is typically the use of interfaces. You can find a neat example here.
After defining an initial model of your domain and gathering as much knowledge about it as you can, you can now start to think about the implementation's architecture. This is were you can start thinking about the architectural patterns. Event driven architecture, clean architecture, MVP, MVVM... It will all depend on your domain. It is your job to know which pattern will fit best. Spoiler alert: this can be extremely hard to do correctly even for experienced engineers, so don't be afraid to fail.
Finally, leave the design patterns for the implementation stage. Their use completely depends on your implementation problems and decisions. Also, DON'T FORCE THEM. Ideally, you will solve a problem and, IF APPLICABLE, you'll see a pattern emerging. Trust me, the last thing you want is to have a case of design patternitis. Anyway, if you need literature on patterns, I totally recommend this book. It's great no matter your level as an engineer.
Further reading:
SOLID principles
Onion Architecture
Clean architecture
Good luck!
You have a background task, and it can be used for a message pump/event queue indeed. Then your foreground task would send requests to this background thread and asynchronously wait for the result.
Have a look at the book "Patterns for Parallel Programming".
It is much better if you check a book for Design Patterns. I really like this one.
For example, if you need to get some data from a particular object, you may need the Observer Pattern to work for you and as soon as the object has the data, you (or another object) get to know this data and can work with it, with another pattern (strategy might work, it really depends on what you have to do).
If you have to do some things at the same time, check also the Singleton pattern (well, check the most important ones!).

Is there a way to prevent keyboard macros from running on a program?

I've developed an online game, sadly there's a select few people who are using recorded keyboard macros using programs like Razer Synapse to automate part of the game process.
This is something I'd like to not allow.
So my question is, is there a way in C++ to determine if a macro is being used to preform input or to determine if the most recent key click triggered was triggered by a human input or programmed input?
My first guess is no... but I could be wrong.
You cannot prevent automation from any client you don't control. The study of algorithms is hundreds of years old, and computers are intended first to be devices of automation. Whatever novelty you come up with will be easily defeated simply because somebody was up to the challenge. That does not mean to say you should avoid solutions which assure bots aren't given a significant advantage, such as speed of input as suggested in the above comments, but if you hope to stop automation altogether you are climbing an endlessly steep hill.
Maybe you should evaluate and consider if rampant automation is an indicator that some aspect of your game mechanics are being viewed as, well, boring. We should strive to provide a player with enough stimulation to want to remain engaged in our games.

how to control one program from other

I want a little help. I know java and little c++. I have seen trainers for games which can set health of player and spawn cars etc. I want to make something similar to that.
For example we have minesweeper running. when i run my java program and click on a button it should call minesweepers function and minesweeper game should show that i won.
So my question is how to establish a connection or something to another program running and calling the program's functions by passing arguments. how is it possible. I heard about reverse engineering and downloaded a program called OllyDBG. And a winject dll injector. i donot know what to do. Combining all these how can i make a program. Please give me ideas or codes or resources helpful.
First you need to reverse-engineer minesweeper to find out the memory location of different variables. Remember that you will probably not be able to run minesweeper's functions due to context, but you can inject code on it to run those. You can read memory easily, though.
To inject code, you must assemble it separately, and then write it in the process virtual space.
In windows API there are several functions that allow opening a process and accessing it memory, but you must have privileges for that.
In summary: To do that, the first thing you need to learn is how to disassemble and understand a program. Only then youll figure out how easy minesweeper is to understand.
BTW: minesweeper stores the map raw in memory. A simple memory inspector will allow you to get the map of it.
Well, your starting sentence was:
"I have seen trainers for games which can set health of player and spawn cars etc. I want to make something similar to that."
Here's a very nice reference code that does what you talked about in C++
http://www.codeproject.com/Articles/7468/Game-Wizard
First strengthen your C++ skills and then study what he does there.
A general description would be that the "victim" process memory is search for a certain value.
Usually something that represents a value that you are aware of - for example, number of bullets of your character.
Usually a big list of location in memory is found at first.
But then, you shoot a bullet, and now the list that you previously found (and only it!) is searched for the new value.
Each step discards the "false positive" finds, until in the end you know the location of the variable that you searched for.
After doing this you are able to change it as well.
Now, going to the general topic - this technique is only a specific approach, and while very helpful in some cases, many times you need stronger and different tools.
Here's a very similar question: How can I find the data structure that represents mine layout of Minesweeper in memory?
I personally find IDA to be an amazing tool for reverse engineering and analyzing an application (both statically and dynamically).
In combination with "idapython" (ida binding for python) it feels unstoppable :)
Reverse engineering requires that you have at least basic knowledge of your target machine architecture - for example, x86 instructions.
Search for IDA tutorials to get the hang of it.
There are many "crackme's" floating around, those are challenges to crack (for educational purposes) varying types of application protections.
It will teach you a lot.
You can also search google for "reverse engineering for beginners".
The web has tons of resources on this topic. The amount of information can be intimidating at first, so make sure you find a basic site that helps you to build your skills gradually.
Another important term that you should know is "hooking". While making it yourself will teach you the most, there are libraries that perform this operation for you.
The idea is to gain control over a certain function.
Whenever anyone calls that function, the control is first passed to your code, and you can decide what to do.
For example, you can decide to simply log this call to a file and call the original function,
or you can do more complicated things.
I found http://tuts4you.com/ to contain many useful tutorials and snippets of information.
Oh, and as people said, Java is not your friend in this case.
C/C++/Assembly probably are.
Starting a completely new topic, especially reverse engineering is tricky in the beginning, but I can assure you it's very rewarding.
Edit:
I have a surprise for you:
http://www.uninformed.org/?v=1&a=7
I simply googled reverse engineering tutorial mine sweeper ;)
Good luck :)

How do you understand a large chunk of code?

I am a fresh college grad student that just started my job. In my ramp up period, I need to learn a lot of product code. There are some design docs but they do not help much.
Can you provide some general techniques to browse and understand huge product code (specifically C++)?
Run it through doxygen. This will generate html documentation which will be helpful even if the code does not have proper doxygen-style comments.
Another good advice is to look through the unit tests, if there are any. If there are no unit tests, a good way to understand the code is to write your own unit tests. The effort to do this will pay for itself many times over.
Use every method available to you (in no particular priority):
Use the product itself and understand what it does
Talk to the devs that maintained it or have worked with it previously
Debug through it and see how data flows and how classes interact ("when I click this button, what exactly happens, who is responsible?")
Look at architecture, UML, or class diagrams
One of my favorites: create your own diagrams of class hierarchies, class interactions, general control flow, high-level components, process/DLL interactions, object lifetimes and management
If they're not totally out-of-date, read the dev/test/user specs (goes well with #1)
Read the documentation on it
Most of all: be tenacious and persistent. If you don't put in the work, don't expect to understand it. If you don't understand something, dig and dig until you do. Software is not magic, it's just hard work :)
Some people will tell you to start with the data structures, but in a large system even that's not terribly helpful much of the time. I can think of four major points:
Take your time. Often, it's more like a whole series of gestalt shifts than it is a single, linear, gradual understanding. So be patient.
No matter how big it is, you should be able to put a breakpoint in and walk it in a debugger. Even in a large, complicated, multi-threaded system, you should be able walk through and see what's happening.
Ask for bugs, and start fixing them, no matter how crazy they seem. It's akin to dropping yourself into a foreign country; you'll pickup the language eventually.
Find a mentor. A jungle guide is invaluable.
I think there have been a few good responses already. My 2c worth...
Not sure what you class as huge (10 KLOC, 1000 KLOC, 10000 KLOC, etc), but one would hope that this is broken down in some way and is not a monolithic single program. Perhaps your management has some guidance on which 'module(s)' you are most likely to be spending time in at the moment. Hopefully this can help break down the problem scope.
Firstly, before you try to understand the code try to understand the product. What does it do? Then how does it do it? What does it interact with? Then how does it interact? etc...
When getting to the code try to understand the high level design and philosophy first, and work on the breadth before the depth. I agree with some of the above re fixing some bugs, but I also strongly suggest you continue to get a handle on the high level even if you need to get into the details to fix some bugs.
I also agree with the above in terms of generating some diagrams for yourself if you can't find any already in existence. And then share them, perhaps a team/product wiki? I'm curious as to why the existing doco does not help very much. Typically this is because this type of doco was generated from the early concepts and the product no longer bears any similarity, but if this is not the case then what can you contribute to this issue. One assumes that where you are today someone else will be in short enough order, and you are in an ideal position to know what essential doco is missing!
If the product is actually 'huge' then you have to accept that you will never be able to hold all of it in your head, so the best thing you can do is be familiar enough to know where to start looking (comes back to understanding the product, and approaching code breadth first).
This is obviously a pretty common question, and it's similar to this one (and the questions related to it): How to understand the design and code flow of any product quickly?
Dig through some of those answers / comments, for starters. Else, we'll just end up repeating them. :)

Need refactoring ideas for Arrow Anti-Pattern

I have inherited a monster.
It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.
To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.
This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.
My question is, what methods would you suggest to refactor or restructure such a thing?
I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.
Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.
Thanks for any and all ideas.
I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.
There is no one thing that will get you out of this. The state machine might be the final form your code takes, but thats not going to help you get there, nor should you decide on such a solution before untangling the mess you already have.
First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test.
Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.
Now Refactor!
A couple things I did that i found useful:
Invert if statements
A huge problem I had was just reading the code when I couldn't find the corresponding else statement, I noticed that a lot of the blocks looked like this
if (someCondition)
{
100+ lines of code
{
...
}
}
else
{
simple statement here
}
By inverting the if I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.
Extract Method
I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.
Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood procedural code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).
Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.
Refactoring to Patterns is a great book to assist in explainging patterns that are helpful in these situations.
You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.
A state machine seems like the logical place to start, and using WF if you can swing it (sounds like you can't).
You can still implement one without WF, you just have to do it yourself. However, thinking of it like a state machine from the start will probably give you a better implementation then creating a procedural monster that checks internal state on every action.
Diagram out your states, what causes a transition. The actual code to process a record should be factored out, and called when the state executes (if that particular state requires it).
So State1's execute calls your "read a record", then based on that record transitions to another state.
The next state may read multiple records and call record processing instructions, then transition back to State1.
One thing I do in these cases is to use the 'Composed Method' pattern. See Jeremy Miller's Blog Post on this subject. The basic idea is to use the refactoring tools in your IDE to extract small meaningful methods. Once you've done that, you may be able to further refactor and extract meaningful classes.
I would start with uninhibited use of Extract Method. If you don't have it in your current Visual Studio IDE, you can either get a 3rd-party addin, or load your project in a newer VS. (It'll try to upgrade your project, but you will carefully ignore those changes instead of checking them in.)
You said that you have code indented 15 levels. Start about 1/2-way out, and Extract Method. If you can come up with a good name, use it, but if you can't, extract anyway. Split in half again. You're not going for the ideal structure here; you're trying to break the code in to pieces that will fit in your brain. My brain is not very big, so I'd keep breaking & breaking until it doesn't hurt any more.
As you go, look for any new long methods that seem to be different than the rest; make these in to new classes. Just use a simple class that has only one method for now. Heck, making the method static is fine. Not because you think they're good classes, but because you are so desperate for some organization.
Check in often as you go, so you can checkpoint your work, understand the history later, be ready to do some "real work" without needing to merge, and save your teammates the hassle of hard merging.
Eventually you'll need to go back and make sure the method names are good, that the set of methods you've created make sense, clean up the new classes, etc.
If you have a highly reliable Extract Method tool, you can get away without good automated tests. (I'd trust VS in this, for example.) Otherwise, make sure you're not breaking things, or you'll end up worse than you started: with a program that doesn't work at all.
A pairing partner would be helpful here.
Judging by the description, a state machine might be the best way to deal with it. Have an enum variable to store the current state, and implement the processing as a loop over the records, with a switch or if statements to select the action to take based on the current state and the input data. You can also easily dispatch the work to separate functions based on the state using function pointers, too, if it's getting too bulky.
There was a pretty good blog post about it at Coding Horror. I've only come across this anti-pattern once, and I pretty much just followed his steps.
Sometimes I combine the state pattern with a stack.
It works well for hierarchical structures; a parent element knows what state to push onto the stack to handle a child element, but a child doesn't have to know anything about its parent. In other words, the child doesn't know what the next state is, it simply signals that it is "complete" and gets popped off the stack. This helps to decouple the states from each other by keeping dependencies uni-directional.
It works great for processing XML with a SAX parser (the content handler just pushes and pops states to change its behavior as elements are entered and exited). EDI should lend itself to this approach too.