Short version:
In my tests with Android 5.0 Lollipop I have noticed android.bluetooth.le.BluetoothLeScanner detects BLE devices less frequently than Android 4.4 KitKat. Why is this and is there an alternative?
Long version:
I am developing an Android application, specifically for the Nexus 7 tablet, that focuses on detecting Bluetooth Low Energy (BLE) devices. The app is mainly interested in the RSSI value of the beacons, to determine their proximity to the tablet. This means I won't need to connect to the BLE device, since the RSSI value is passed to the scan callback when the device is detected.
In Android 4.4 KitKat, when I call BluetoothAdapter.startLeScan(LeScanCallback), my callback gets called only ONCE for every detected BLE device. (I have seen some discussions claim that this behaviour can differ per device) However, I am interested in the constantly changing RSSI value, so the currently recommended way is to continuously do startLeScan and stopLeScan with a set interval (250ms in my case):
public class TheOldWay {
private static final int SCAN_INTERVAL_MS = 250;
private Handler scanHandler = new Handler();
private boolean isScanning = false;
public void beginScanning() {
scanHandler.post(scanRunnable);
}
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (isScanning) {
adapter.stopLeScan(leScanCallback);
} else if (!adapter.startLeScan(leScanCallback)) {
// an error occurred during startLeScan
}
isScanning = !isScanning;
scanHandler.postDelayed(this, SCAN_INTERVAL_MS);
}
};
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// use the RSSI value
}
};
}
Essentially this gives me the required results, but this process is very resource intensive and eventually leads to an unresponsive bluetooth adapter.
For these reasons I upgraded my Nexus 7 to Android 5.0 Lollipop, to see whether my BLE issues would be fixed. In Lollipop BluetoothAdapter.startLeScan(LeScanCallback) is deprecated and replaced with a new API that allows for some more control over the scanning process. From my first tests, it appears startScan does not continuously call my callback (on my Nexus 7) when the RSSI values change, so I still need to use the startScan / stopScan implementation:
#TargetApi(21)
public class TheNewWay {
private static final int SCAN_INTERVAL_MS = 250;
private Handler scanHandler = new Handler();
private List<ScanFilter> scanFilters = new ArrayList<ScanFilter>();
private ScanSettings scanSettings;
private boolean isScanning = false;
public void beginScanning() {
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
scanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
scanSettings = scanSettingsBuilder.build();
scanHandler.post(scanRunnable);
}
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
BluetoothLeScanner scanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
if (isScanning) {
scanner.stopScan(scanCallback);
} else {
scanner.startScan(scanFilters, scanSettings, scanCallback);
}
isScanning = !isScanning;
scanHandler.postDelayed(this, SCAN_INTERVAL_MS);
}
};
private ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
int rssi = result.getRssi();
// do something with RSSI value
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
// a scan error occurred
}
};
}
As you can see, I have configured the scanner using the ScanSettings class, which allows you to set the scanMode. I use ScanSettings.SCAN_MODE_LOW_LATENCY, which has the following documentation: "Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground." Sounds exactly like what I want, but unfortunately I only get a beacon detect every 15 - 30 seconds, where the KitKat version shows me the same beacon every 1 - 2 seconds on this scan interval.
Do you have any idea what could be the reason for this difference? Am I missing something, maybe some new settings? Are there alternative ways of doing the above?
Thanks a lot in advance!
Abel
PS: I wanted to include more links to resources I've used, but I don't have the rep points for it yet.
I have gotten very different results with a Nexus 5 running the new Android 5.0 scanning APIs. Detections of BLE packets came in at near real time when using SCAN_MODE_LOW_LATENCY, at every 100ms for BLE beacons transmitting at 10Hz.
You can read the full results here:
http://developer.radiusnetworks.com/2014/10/28/android-5.0-scanning.html
These tests are based off of running the open source Android Beacon Library 2.0's experimental android-l-apis branch here.
It is not obvious what the difference is in your test results, but it is possible that starting and stopping scanning is changing the results.
EDIT: it is possible the hardware is the difference. See a report of similar timings on the Nexus 4: https://github.com/AltBeacon/android-beacon-library/issues/59#issuecomment-64281446
I don't have 50 reputation for a comment yet, so bear with me, this comment will be in the form of an answer. In your code, shouldn't this part:
if (isScanning) {
scanner.startScan(...)
be this instead:
if (!isScanning) {
scanner.startScan(...)
Because following your code, you're calling stopScan() before starting a scan. It may not have a direct effect on the result if the stopScan() method is idempotent/safe. But you know, for the sake of code intelligibility you should edit the question. And do the same to your code, sometimes byzantine things are at play ;)
Have you tried larger values for SCAN_INTERVAL_MS? If yes, how large?
I have experienced very similar results with my Nexus 4, in both KitKat and Lollipop.
With KitKat the bluetooth adapter also eventually went unresponsive; at first I though that it could be related to a short scan interval (200ms) but increasing that number to even a second didn't help, in that matter I found that, when unresponsive disabling and enabling the adapter programmatically, sometimes solves the problem. Unfortunately I can't say that it works all the time.
Now with Lollipop, in which I had high hopes to solve this issues, I experienced the same behaviour that you describe. I also had to use the startScan / stopScan implementation, getting similar results regarding the detection times. Sadly, I haven't found a work around to get results more quickly.
Based on what you describe I suppose it could be a hardware issue, even though the Nexus 7 and Nexus 4 are from different manufacturers (Asus and LG).
I know I'm not providing much help here besides trying to answer your question about you missing something; I don't think so, I think the problem is something like the hardware or the bluetooth API that still doesn't behave the way it should across different devices.
Beyond API 21 android uses SCAN_MODE_LOW_POWER by default.
SCAN_MODE_LOW_POWER
Try SCAN_MODE_BALANCED and see if it gets better.
SCAN_MODE_BALANCED
if you search for BW13_DayOne_Session1 Bluetooth Advanced on google, you will find a pdf document that gives you the latencies for devices based on the settings for discovery (see page 8). I'm guessing your problem has to do with these timings. You can verify by figuring out the advertising configuration for the device you are testing (Adv Int, Duty Cycle) then figure out what the API settings are doing for configuring the scan interval, etc. Once you have these, you can then use that table to interpolate to see if your getting the results you expect.
I know this is a software site, but often when interfacing with hardware you need to know the protocol otherwise your shooting in the dark.
Related
I’m wondering how do I go about establishing a serial port communication between Arduino Uno (as my input) and Godot game engine (as my output)? Context is, I'm trying to use sensors on Arduino to move/place objects on Godot, thus I need the serial port code or guidance on how to go about achieving that connection.
Any help is appreciated, thank you everyone!
You can try plugin GDSerCommPlugin. But it is work in progress and i didnt test it so i dont know if it is usable.
Since it's a long time this question was asked, I think that an update is welcome.
Since Godot 3.0, C# is fully supported, I'm using Godot 3.3.2 and my conclusion about dealing with serial communication in Godot is : use C#
You'll keep all the multi platform development advantage of Godot without writing a single (low level) line of code, here is a snipped:
using System.IO.Ports; // for .NET SerialPort
Then in your class if you want to open the port (assuming "SerialPort port" is defined):
port = new SerialPort(portName, (Int32)baudRate, Parity.None, 8, StopBits.One);
Then use the _Process to read the data:
public override void _Process(float delta)
{
if (port != null)
{
if (port.BytesToRead > 0)
{
string serData = port.ReadExisting();
string[] str = serData.Split('\n'); // Just an example
parseLines(str); // Your implementation
}
}
}
Note1: "DataReceived" event from SerialPort doesn't work (I don't know why but I think this is due to the different context) but with Godot this function is useless since you can check and parse directly the data in the _Process function.
Note2: For efficiency it's better to use the ReadExisting() function (and parse lines yourself) than the Readline() function in a loop in the _Process function.
Note3: Sending to serial port is immediate eg:
port.Write("Hello\r");
My hybrid Cordova Android app uses one custom plugin in which I do a great deal of background work at intervals of ca 30 minutes. Up until now I have been using AlarmManger with a setInexact alarm to perform the work. The only real issue I have with that route is that the alarm does not survive a reboot. Given that I am now only supporting Android 6 (API 23)+ devices I am now experimenting with replacing AlarmManager with JobScheduler. My efforts thus far are shown below
public class UnyService extends JobService
{
#Override
public boolean onStartJob(JobParameters params)
{
UnyHandler.sendMessage(Message.obtain(UnyHandler,1,params));
return true;
}
#Override
public boolean onStopJob(JobParameters params)
{
UnyHandler.removeMessages(1);
return false;
}
where I am using a Handler to perform the actual work. The code for Handler is shown below
private Handler UnyHandler = new Handler(new Handler.Callback()
{
#Override
public boolean handleMessage(Message msg)
{
Feedback.postBackInfo("Handled it!");
jobFinished((JobParameters)msg.obj,false);
return true;
}
});
I then use the following code to get the job up and running
private void launchTimerJob()
{
timerJob =
(JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(1,new
ComponentName(Utils.packName,UnyService.class.getName()));
builder.setPeriodic(30000);
builder.setPersisted(true);
builder.setBackoffCriteria(30000,JobInfo.BACKOFF_POLICY_LINEAR);
if (0 >= timerJob.schedule(builder.build()))
Feedback.postBackInfo("Job Build Error");
else Feedback.postBackInfo("Job Created and Scheduled");
}
where Feedback and Utils are other classes in my app which provide support services. To facilitate testing I am using a relatively small period of 30 seconds.
When I install and start the app the plugin init code calls launchTimerJob() and I get the "Job Created and Scheduled" notification back as expected.
From that point forward I had expected to get Handled It! notifications from Handler above at intervals of roughly 30s. A notification has turned up on the odd occasion but a totally arbitrary time measuring from App startup and has not obliged by repeating. Clearly, I am doing something wrong here.
Android docs could do a better job of mentioning that the minimum interval allowed for periodic jobs is 900,000 milliseconds, i.e.
15 minutes !!!!
I gather that prior to API 24 (Nogat) it was possible to use smaller intervals but no longer. Be wary of the various JobScheduler tutorials you will find out there. There are many that are quite dated and Android Jobs appears to be a still evolving API.
My own reason for originally using AlarmManager was to enable background tasks to be performed when the app was, well, backgrounded. However, with the coming of doze mode this strategy fails since the app will simply not get broadcast messages when the device is dozing.
Consider the following strategy instead
When the app is foregrounded you can quite simply use a Handler to manage periodic tasks - even those that happen at an interval of a few seconds.
No normal app should ever have to carry out background tasks at that frequency (every few seconds) when the phone is dozing - and when that is required there is a route via a specific request for the app to be exempted from battery optimizations. In such instances a periodic JobScheduler with a 15 minute period is the best you can do.
Our app is crashing on Android O due to the new background execution limits. We are on Firebase version 10.2.1, which is the one that added Android O support.
Seems like an issue with Firebase? Or is there some change needed to support this on our end?
java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.firebase.INSTANCE_ID_EVENT pkg=my.package.name cmp=my.package.name/my.package.name.MyFcmIdService (has extras) }: app is in background uid UidRecord{30558fa u0a327 RCVR idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1505)
at android.app.ContextImpl.startService(ContextImpl.java:1461)
at android.content.ContextWrapper.startService(ContextWrapper.java:644)
at android.support.v4.content.WakefulBroadcastReceiver.startWakefulService(WakefulBroadcastReceiver.java:99)
at com.google.firebase.iid.zzg.b(zzg.java:9)
at com.google.firebase.iid.zzg.a(zzg.java:72)
at com.google.firebase.iid.zzg.a(zzg.java:2)
at com.google.firebase.iid.FirebaseInstanceIdService.a(FirebaseInstanceIdService.java:23)
at com.google.firebase.iid.FirebaseInstanceIdService.a(FirebaseInstanceIdService.java:34)
at com.google.firebase.iid.FirebaseInstanceId.<init>(FirebaseInstanceId.java:31)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(FirebaseInstanceId.java:47)
at com.google.firebase.iid.FirebaseInstanceId.a(FirebaseInstanceId.java:4)
at com.google.firebase.iid.FirebaseInstanceIdService.a(FirebaseInstanceIdService.java:19)
at com.google.firebase.iid.FirebaseInstanceIdService.b(FirebaseInstanceIdService.java:35)
at com.google.firebase.iid.zzb$zza$1.run(zzb.java:24)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Update Upgrading to 11.4.2 resolves this issue.
#KaMyLL is right. I had the same issue with our app and could solve it by replacing the IntentService (which we have started within onTokenRefresh()) with an JobIntentService.
Because I found the JobScheduler and JobIntentService docs a bit confusing, I would like to some everything up with some code snippets. I hope this makes everything clear to everyone having this issue.
What is causing this issue?
Due to the new Background Execution Limits of Android 8, you should not start background services anymore when the app could be in background:
While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.
And also:
In many cases, your app can replace background services with JobScheduler jobs.
So for Android 7.x and below, using startService() when the app is in background is (as far as I know) no problem. But in Android 8, this results in a crash. In consequence, you should use a JobScheduler now. The behavioral difference between JobScheduler and an IntentService is that an IntentService is executed immediately. On the other hand, a job enqueued to a JobScheduler is not guaranteed to be executed immediately. The Android OS will determine when there is a good point of time to do so in order to be more energy efficient. So there might be a delay. And I have no idea so far how long this could take.
So one solution could be to check the OS version and branch your code using if-else. Fortunately, the support library helps us to solve this in a more elegant way without duplicating any code: JobIntentService, which basically does this for you under the hood.
How to reproduce the issue?
The first quote above states that the app still "has a window of several minutes in which it is still allowed to create and use services.", so in order to reproduce and debug the issue (with the example of onTokenRefresh() in Firebase), you could set a breakpoint before your start your service with startService(). Close the app and wait there for 5-10 minutes. Continue the execution and you will see the IllegalStateException from this question.
Being able to reproduce the issue as fundamental to make sure that our fixes really solve the problem.
How to migrate my IntenService to JobIntentService?
I use FirebaseInstanceIdService.onTokenRefresh() as an example:
a) Add the BIND_JOB_SERVICE permission to your service:
<service android:name=".fcm.FcmRegistrationJobIntentService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"/>
b) Instead of extending from IntentService, simply extend from android.support.v4.app.JobIntentService, rename the onHandleIntent(Intent) method to onHandleWork(Intent), and add a enqueueWork(Context, Intent) convenient function:
public class FcmRegistrationJobIntentService extends JobIntentService
{
// Unique job ID for this service.
static final int JOB_ID = 42;
// Convenience method for enqueuing work in to this service.
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, FcmRegistrationJobIntentService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
// the code from IntentService.onHandleIntent() ...
}
}
c) Start the job using the enqueueWork() convenient function:
public class ComfyFirebaseInstanceIdService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
Intent intent = new Intent(this, FcmRegistrationJobIntentService.class);
// startService(intent);
FcmRegistrationJobIntentService.enqueueWork(this, intent);
}
}
I hope this example is helpful. At least after following these steps, I was not able to reproduce the issue on my Android 8 device anymore, and it continues to work an my Android 7 device.
Update
as FirebaseInstanceIdService deprecated we should remove this from the code, and use onNewToken from FirebaseMessagingService instead.
I've done some research about it and the best option is to transform IntentService into JobIntentService available in app compat library. It would behave like IntentService on all pre-Oreo devices. On Android 8 and above it will enqueue job to android system JobScheduler. This job by default have set deadline parameter to 0, so theoretically it should fire as fast as possible.
as of today (26/10/2018), FirebaseInstanceIDServie isdeprecated, try this to fix the above issue link
I want to put the serial communication with an external device to a second thread, c#.
Here there is my first thread doing some stuff.
And there is the serial worker, the second thread:
It opens the serial port
It asks the external serial device regulary: Are you alive?
It receives queries from the first thread with a string and an int like: "Command2", 33 and it should give this to the external serial device.
Sometimes there comes an answer from the external serial device back with a string and an int like: "Command4", 55 and the second thread should give this to the first thread and it should start a process there.
The second thread also does own things like error detection which I want to keep free the first thread of.
Serial communication itself works fine but I have problems with threads, delegates, BeginInvokes, EventHandlers, etc.
My first thread:
Class MainProgramme
{
internal void StartSerialCommunication
{
=> Here I want the second thread to open the serial port and I want to start the regulary serial device check, all in the
second thread.
}
internal bool SerialCommand(string s, int i)
{
=> Here I want to give the command s and i to the second thread asynchronously. That means this process does not wait for an answer from the second thread.
}
The following process should be fired by the second thread because the second thread has received some important data
from the external serial device.
internal void SerialAnswered
{
=> Here I want to get the string and the int from the second device back.
}
}
My second thread:
Class SerialCommunication
{
internal bool SerialDeviceIsAlive = true;
public bool SerialOpen
{
SerialPortMsp.Open();
RegularyDeviceCheckTimer.Enabled = true;
return true;
}
private void RegularyDeviceCheckTimer_Tick(System.Object
sender, System.EventArgs e)
{
if SerialDeviceIsAlive == true)
{
SerialDeviceIsAlive == false;
}
else
{
=> Here I want to inform the first thread that the answer from the external serial device is missing.
}
SerialSend("AreYouAlive");
}
public void SerialReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
IAmAlive = true;
int buff = SerialPortMsp.ReadExisting();
if (buff.IndexOf(new string('\n', 1)) > 0)
{
=> Here I want to inform the first thread that the answer was buff.
}
}
public bool SerialSend(string SerialCommand)
{
SerialPortMsp.Write(SerialCommand.ToCharArray(), 0,
SerialCommand.Length);
return true;
}
}
I need help in calling processes and transferring data between the two threads.
I think both thread1 and thread2 have their "own" execution path, and you can not force them to "interrupt" and do something with the data that you built in the other thread.
What you can do is that you "plan" for the possibility that there is something ready in the other thread that might need your attention in the current thread. Hence, both thread1 and thread2 need a code that regularly checks if there is something "ready" in the other thread.
If you plan to do other things in thread1 you still need to build in a regular check/poll for the results of thread2 and vica versa.
The concrete communication between the threads might be implemented with a queue in each direction. In .NET 4.0 there is a ConcurrentQueue class for thread-safe producer/consumer implementation. When thread1 has a command it should queue it in the command queue, while thread2 should regularly check if there are commands waiting. When thread2 has a result ready, it should queue it in a result queue, while thread1 should regularly check if there is a result and run the processing code accordingly.
Having all this said, I think you should consider once more, if your solution with exactly these two threads is really what you need. However, this depends on the details of your requirements (e.g. what other things thread1 should do in the meanwhile, and what the processing of the command result means, can it run parallel, etc).
My suggestion would be to align your design based on the producer/consumer pattern. That is a typical concurrency task and you will find a lot of explanations and optimized solutions (e.g. where the consumer does not have to poll the queue, but it can sleep on a waithandle, semaphore, or some other construct without using CPU and it can be waken up by the producers if there is something to consume).
In your case you could use this pattern twice. The CommandProducer is the entity that creates the commands and feeds the CommandConsumer (that can consume it by passing it to the serial line). On the back way you have the CommandResultProducer that reads the serial line and passes the result to the CommandResultConsumer to do something with the result. Aligning your code like this would result in a more flexible and clear solution, and you can even increase the number of consumer or producer threads if it turns out to be practical.
Lets assume I am a game and I have a global int* that contains my health. A game trainer's job is to modify this value to whatever in order to achieve god mode. I've looked up tutorials on game trainers to understand how they work, and the general idea is to use a memory scanner to try and find the address of a certain value. Then modify this address by injecting a dll or whatever.
But I made a simple program with a global int* and its address changes every time I run the app, so I don't get how game trainers can hard code these addresses? Or is my example wrong?
What am I missing?
The way this is usually done is by tracing the pointer chain from a static variable up to the heap address containing the variable in question. For example:
struct CharacterStats
{
int health;
// ...
}
class Character
{
public:
CharacterStats* stats;
// ...
void hit(int damage)
{
stats->health -= damage;
if (stats->health <= 0)
die();
}
}
class Game
{
public:
Character* main_character;
vector<Character*> enemies;
// ...
}
Game* game;
void main()
{
game = new Game();
game->main_character = new Character();
game->main_character->stats = new CharacterStats;
// ...
}
In this case, if you follow mikek3332002's advice and set a breakpoint inside the Character::hit() function and nop out the subtraction, it would cause all characters, including enemies, to be invulnerable. The solution is to find the address of the "game" variable (which should reside in the data segment or a function's stack), and follow all the pointers until you find the address of the health variable.
Some tools, e.g. Cheat Engine, have functionality to automate this, and attempt to find the pointer chain by themselves. You will probably have to resort to reverse-engineering for more complicated cases, though.
Discovery of the access pointers is quite cumbersome and static memory values are difficult to adapt to different compilers or game versions.
With API hooking of malloc(), free(), etc. there is a different method than following pointers. Discovery starts with recording all dynamic memory allocations and doing memory search in parallel. The found heap memory address is then reverse matched against the recorded memory allocations. You get to know the size of the object and the offset of your value within the object. You repeat this with backtracing and get the jump-back code address of a malloc() call or a C++ constructor. With that information you can track and modify all objects which get allocated from there. You dump the objects and compare them and find a lot more interesting values. E.g. the universal elite game trainer "ugtrain" does it like this on Linux. It uses LD_PRELOAD.
Adaption works by "objdump -D"-based disassembly and just searching for the library function call with the known memory size in it.
See: http://en.wikipedia.org/wiki/Trainer_%28games%29
Ugtrain source: https://github.com/sriemer/ugtrain
The malloc() hook looks like this:
static __thread bool no_hook = false;
void *malloc (size_t size)
{
void *mem_addr;
static void *(*orig_malloc)(size_t size) = NULL;
/* handle malloc() recursion correctly */
if (no_hook)
return orig_malloc(size);
/* get the libc malloc function */
no_hook = true;
if (!orig_malloc)
*(void **) (&orig_malloc) = dlsym(RTLD_NEXT, "malloc");
mem_addr = orig_malloc(size);
/* real magic -> backtrace and send out spied information */
postprocess_malloc(size, mem_addr);
no_hook = false;
return mem_addr;
}
But if the found memory address is located within the executable or a library in memory, then ASLR is likely the cause for the dynamic. On Linux, libraries are PIC (position-independent code) and with latest distributions all executables are PIE (position-independent executables).
EDIT: never mind it seems it was just good luck, however the last 3 numbers of the pointer seem to stay the same. Perhaps this is ASLR kicking in and changing the base image address or something?
aaahhhh my bad, i was using %d for printf to print the address and not %p. After using %p the address stayed the same
#include <stdio.h>
int *something = NULL;
int main()
{
something = new int;
*something = 5;
fprintf(stdout, "Address of something: %p\nValue of something: %d\nPointer Address of something: %p", &something, *something, something);
getchar();
return 0;
}
Example for a dynamicaly allocated varible
The value I want to find is the number of lives to stop my lives from being reduced to 0 and getting game over.
Play the Game and search for the location of the lifes variable this instance.
Once found use a disassembler/debugger to watch that location for changes.
Lose a life.
The debugger should have reported the address that the decrement occurred.
Replace that instruction with no-ops
Got this pattern from the program called tsearch
A few related websites found from researching this topic:
http://deviatedhacking.com/index.php?/topic/75-dynamic-memory-allocation/
http://www.edgeofnowhere.cc/viewforum.php?f=183
http://www.oldschoolhack.de/tutorials/Theories%20and%20methods%20of%20code-caves.htm
http://webcache.googleusercontent.com/search?q=cache:4wzMzFIZx54J:gamehacking.com/forums/tutorials-beginners/11597-c-making-game-trainer.html+reading+a+dynamic+memory+address+game+trainer&cd=2&hl=en&ct=clnk&gl=au&client=firefox-a (A google cache version)
http://www.codeproject.com/KB/cpp/codecave.aspx
The way things like Gameshark codes were figured out were by dumping the memory image of the application, then doing one thing, then looking to see what changed. There might be a few things changing, but there should be patterns to look for. E.g. dump memory, shoot, dump memory, shoot again, dump memory, reload. Then look for changes and get an idea for where/how ammo is stored. For health it'll be similar, but a lot more things will be changing (since you'll be moving at the very least). It'll be easiest though to do it when minimizing the "external effects," e.g. don't try to diff memory dumps during a firefight because a lot is happening, do your diffs while standing in lava, or falling off a building, or something of that nature.