Cant modify module IAT to hook API - Windows Mobile Software Development

This may be better served in the development and hacking forum. Mods please move?
I am trying to hook the keybd_event API in the keypad. I have found the address of the import entry for keybd_event in the keypad.dll's IAT. I have done so by disassembling the keypad.dll and finding the offset from an exported function to that IAT entry. At runtime, I have added my own service (in order to get my dll loaded into services.exe). When loaded, I use GetModuleHandle and GetProcAddress to find that exported function then use the known offset to find the IAT entry. I have verified that I have the right memory location by comparing the pointer to the module's location using remote process viewer.
The problem is that I cannot read from or write to the IAT. My code crashes when I try. IsBadReadPtr and IsBadWritePtr tell me that I cant read or write to this memory location. Even a call to VirtualProtect to set it to PAGE_EXECUTE_READWRITE will not work. The call fails. How can I get access to this memory?
This simple test code exe shows that all the memory in the code section of keypad.dll is writeable. As soon as I hit section 2 which contains the IAT The call starts failing. Once I hit section 3 it succeeds again (the hard coded PID and address come from remote process viewer and my service dll; I debugged to find where the read calls fail).
Code:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
DWORD PID = 239927214, addr = 2061766572, read = 0, sz = 0;
HANDLE pr;
BOOL ans1;
_SetKMode SetKMode;
SetKMode = (_SetKMode)GetProcAddress(GetModuleHandle(L"coredll.dll"), L"SetKMode");
ans1 = SetKMode(true);
pr = OpenProcess(0, 0, PID);
while(ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
while(!ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
while(ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
//ans4 = WriteProcessMemory(pr, ptr2, &mkep, 4, &p4);
CloseHandle(pr);
return 0;
}
What do I need to do to get access? Calls to VirtualProtect and SetKMode do nothing. Any ideas? Thanks!

Nevermind! It seems I was not modifying the correct location. I was trying to modify the table that simply lists imports. I found where the actual function pointer is stored.

Related

Hook API function WM6

I'm trying to hook api function "NKDbgPrintfW" from coredll.dll.
I use import table in-memory patch. It works fine for main module (exe file).
It hooks all calls from exe, but does not from dll it uses.
I think root of problem is that exe and loaded dlls use own import table and I patch only exe's one.
I use next function to hook exe api calls:
Code:
DWORD ic_PatchProcImports ( HANDLE hProc, DWORD dFind, DWORD dReplace )
{
DWORD ret = 0;
/* GODMODE ON */
BOOL bOldKMode = SetKMode ( TRUE );
DWORD dOldPerms = SetProcPermissions ( 0xFFFFFFFF );
/* get process ptr prom handle */
HDATA * hProcHD = ( HDATA * ) ( 0x80000000 | ( ( DWORD ) hProc & HANDLE_ADDRESS_MASK ) );
PROCESS * prc = ( PROCESS * ) hProcHD->pvObj;
/* get imports sections */
struct ImpHdr * blockptr, * blockstart;
blockstart = ( struct ImpHdr * ) MapPtrProc ( prc->e32.e32_vbase + prc->e32.e32_unit[IMP].rva, prc );
/* iterate thru imports sections */
for ( blockptr = blockstart; blockptr->imp_lookup; ++blockptr )
{
DWORD dOldProtect, tmp;
/* get vectors ptr */
DWORD * vectors = ( DWORD * ) MapPtrProc ( prc->e32.e32_vbase + blockptr->imp_address, prc );
/* count vectors */
DWORD * vptr = vectors;
while ( * vptr ) ++vptr;
DWORD vcnt = ( vptr - vectors );
/* try to unlock imports section memory */
if ( VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), PAGE_EXECUTE_READWRITE, &dOldProtect ) )
{
/* find&replace */
for ( UINT i = 0; i < vcnt; ++i )
{
if ( vectors[i] == dFind )
{
vectors[i] = dReplace;
++ret;
}
}
/* lock back */
VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), dOldProtect, &tmp );
}
}
/* GODMODE OFF */
SetProcPermissions ( dOldPerms );
SetKMode ( bOldKMode );
/* */
return ret;
}
I tried to find import table in loaded dll module but failed.
Here is the code I used:
Code:
DWORD ic_PatchModuleImports ( HANDLE hProc, Module* mod, DWORD dFind, DWORD dReplace )
{
DWORD ret = 0;
/* GODMODE ON */
BOOL bOldKMode = SetKMode ( TRUE );
DWORD dOldPerms = SetProcPermissions ( 0xFFFFFFFF );
/* get process ptr prom handle */
HDATA * hProcHD = ( HDATA * ) ( 0x80000000 | ( ( DWORD ) hProc & HANDLE_ADDRESS_MASK ) );
PROCESS * prc = ( PROCESS * ) hProcHD->pvObj;
/* get imports sections */
ImpHdr *blockptr, *blockstart;
blockstart = ( ImpHdr * ) MapPtrProc(mod->e32.e32_vbase + mod->e32.e32_unit[IMP].rva, prc);
/* iterate thru imports sections */
for ( blockptr = blockstart; blockptr->imp_lookup; ++blockptr )
{
// NKDbgPrintfW(L"%s", blockptr->imp_dllname);
//DWORD dOldProtect, tmp;
/* get vectors ptr */
DWORD * vectors = ( DWORD * ) MapPtrProc(mod->e32.e32_vbase + blockptr->imp_address, prc);
/* count vectors */
DWORD * vptr = vectors;
while ( * vptr ) ++vptr;
DWORD vcnt = ( vptr - vectors );
/* try to unlock imports section memory */
//if ( VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), PAGE_EXECUTE_READWRITE, &dOldProtect ) )
{
/* find&replace */
for ( UINT i = 0; i < vcnt; ++i )
{
NKDbgPrintfW(L"Serach for: %x; Found: %x", dFind, vectors[i]);
if ( vectors[i] == dFind )
{
vectors[i] = dReplace;
++ret;
}
}
/* lock back */
// VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), dOldProtect, &tmp );
}
}
/* GODMODE OFF */
SetProcPermissions ( dOldPerms );
SetKMode ( bOldKMode );
/* */
return ret;
}
I'm looking for any way to hook this function, but I prefer in-memory import table patch..
Hello!
Perhaps this will help:
http://forum.xda-developers.com/showthread.php?t=372496
I am also working on a program that needs hooks. My problem right now is that I need to create the header with all the structure definitions (PROCESS, THREAD, ect). I found this but it is most likely for an older CE version as it was written in 2003:
http://nah6.com/~itsme/cvs-xdadevtools/itsutils/old/cenk.h
Do you have these definitions for wince 5.x?
I think, you can find it in Windows Mobile Platform SDK .
MS sells that SDK, but if you google it, you'll find a place where you can download it for free
I was working on a similar problem but I decided to make a generic hook that didn't rely only on import table. Thanks to itutils I was able to hook some functions until when I found out that there two methods for making api calls, the standard one and the "speedy" one. I wasn't able to hook any function that was using the second method and after a bit I gave up. How did you overcome this problem?
Any suggestion is welcome, thank you
I still have not solved my problem. I am trying to hook calls to keybd_event in coredll from keypad.dll. I think the root of the problem is that that keypad.dll is in ROM. Therefore the thunk table that is actually inside keypad.dll is not readable or writeable at runtime. I think there is a thunk table created in RAM somewhere else where the function pointers are actually stored. I can find it by analyzing keypad.dll and finding the hex location to where the runtime thunk table is, but I cant find a way to figure it out at runtime so that my hook will work with any dll.
I use the PerformCallback4 DLL hooking and it's working with ROM files. But I'd also be interested if there's a way to inject into a process without needing to load a separate DLL.
Well process injection is not my problem. I am trying to hook calls from a service dll. All I did was add my dll as a service and I am kindly loaded at boot. Its the hooking I cant get to work. How are you accomplishing the hook? I just want to hook all calls from other services to keybd_event.
What _exactly_ do you guys want to do? I may be able to assist.
I know the answers to most questions I see here, but I will simply not give out the code to do this, because it is "dangerous" code. By that I do not mean it is not somewhat reliable, but dangerous to commercial developers as these techniques allow you to crack pretty any commercial app with minimal effort...
(see my notice about having easily bypassed the MS Marketplace "advanced protection" on various news sites for an example of how bad this can be)
Actually I'd be curious to know how to hook an API that can use the kmode speedup, that is one that's using g_pKmodeEntries. I'm not interesting into cracking anything but at this point I'm curious to know how to go ahead.
Thanx for any help.
I heard that the DLL injection hooks won't work for WinCE 6.0 (--> WM 7) but what about the mentioned "kmode speedup"?
bbbird1 said:
Actually I'd be curious to know how to hook an API that can use the kmode speedup, that is one that's using g_pKmodeEntries. I'm not interesting into cracking anything but at this point I'm curious to know how to go ahead.
Thanx for any help.
Click to expand...
Click to collapse
Well there are various ways to patch functions out. The problem is that there are several ways that a kernel function can ultimately be called. Of course there are also various ways to go about patching these functions. To name a few:
(1) Patch the apiset tables and overwrite the function address the trap jumps to. If this is the same table and address are used for the g_pKmodeEntries jump I am not sure - you would have to do some IDA'ing / testing to figure that one out
(2) Patch the import tables of the executable / dll calling this function, if you have a specific target in mind (with some small trickery this can be adapted to also patch 'dynamic imports', i.e. GetProcAddress, even after the call was made)
(3) Patch the export table of coredll (actually if this one matches your wishes, I usually use 4 instead)
(4) Patch the function inside coredll directly by (saving first and then) overwriting the first few instructions with a jump to your code
(5) Patch the actual function inside nk or the other exe server (closely related to 4)
Each method has it's own pros and cons, injection/controlled-leak/code requirements and may or may not work with certain way of calling the function. Some of these patches are much more difficult to do than others...
You'd have to figure out for your function which method might actually work. For example I usually have great results with method 4, however it will not catch some ways of kernel-internal calls, so you have to confirm first with some heavy IDA'ing to see if internal calls exist (completely bypassing coredll, for most functions they actually don't). Unfortunately that I recall I have not tried patching any g_pKmodeEntries intentionally (as in I might have patched such functions, but not knowingly).
RAMMANN said:
I heard that the DLL injection hooks won't work for WinCE 6.0 (--> WM 7) but what about the mentioned "kmode speedup"?
Click to expand...
Click to collapse
Well we'd pretty much have to start from scratch again, figuring a lot of stuff out, but I'm sure we'll find new and exciting ways of hooking kmode speedup might still be there, though, but likely in a different form.
Chainfire said:
What _exactly_ do you guys want to do? I may be able to assist.
I know the answers to most questions I see here, but I will simply not give out the code to do this, because it is "dangerous" code. By that I do not mean it is not somewhat reliable, but dangerous to commercial developers as these techniques allow you to crack pretty any commercial app with minimal effort...
(see my notice about having easily bypassed the MS Marketplace "advanced protection" on various news sites for an example of how bad this can be)
Click to expand...
Click to collapse
Hello chainfire! I am trying to hook keyboard events comming from the keypad driver. There is a service that runs to detect key interrupts and when it does detect them it calls keybd_event to broadcast the event. keybd_event is in coredll. The keypad service is loaded from keypad.dll (in most ROMs). So I want to hook calls from keypad.dll to keybd_event in coredll. The problem is that I want it to work regardless of ROM version and there are different versions of keypad.dll, and some ROMs dont have it at all. Therefore I want to hook all calls to keybd_event from services. I added my dll as a service so injection method is not a problem. Now I need to hook.
Using IDA I found the address of the IAT in keypad, but the IAT that exists in the dll itself is not readable or writeable. It seems that there is a thunk table that gets created in RAM separate from where the dll is loaded. Each process seems to create it's own RAM thunk table for loaded dlls (my guess is just those in ROM). I dont know how to programmatically find these thunk tables.
Do I make sense? This is of course targeting WM6.x (wce5). I just need some way to hook calls to keybd_event from all dlls loaded in the current process. Some of those dlls may be in ROM but they need to be hooked too.
Chainfire said:
Well there are various ways to patch functions out. The problem is that there are several ways that a kernel function can ultimately be called. Of course there are also various ways to go about patching these functions. To name a few:
(1) Patch the apiset tables and overwrite the function address the trap jumps to. If this is the same table and address are used for the g_pKmodeEntries jump I am not sure - you would have to do some IDA'ing / testing to figure that one out
(2) Patch the import tables of the executable / dll calling this function, if you have a specific target in mind (with some small trickery this can be adapted to also patch 'dynamic imports', i.e. GetProcAddress, even after the call was made)
(3) Patch the export table of coredll (actually if this one matches your wishes, I usually use 4 instead)
(4) Patch the function inside coredll directly by (saving first and then) overwriting the first few instructions with a jump to your code
(5) Patch the actual function inside nk or the other exe server (closely related to 4)
Each method has it's own pros and cons, injection/controlled-leak/code requirements and may or may not work with certain way of calling the function. Some of these patches are much more difficult to do than others...
You'd have to figure out for your function which method might actually work. For example I usually have great results with method 4, however it will not catch some ways of kernel-internal calls, so you have to confirm first with some heavy IDA'ing to see if internal calls exist (completely bypassing coredll, for most functions they actually don't). Unfortunately that I recall I have not tried patching any g_pKmodeEntries intentionally (as in I might have patched such functions, but not knowingly).
Well we'd pretty much have to start from scratch again, figuring a lot of stuff out, but I'm sure we'll find new and exciting ways of hooking kmode speedup might still be there, though, but likely in a different form.
Click to expand...
Click to collapse
I like the sound of (3). Why Use (4) instead? How do you find the export table programmatically? If I use this method, as long as my service is loaded first it should work.
Ok I just tried something and it worked. It seems that these RAM thunk tables are always loaded at 0x01bb5000 for every process. The following code worked:
Code:
coremod = GetModuleHandle(L"coredll.dll");
o_keybd_event = (_keybd_event)GetProcAddress(coremod, L"keybd_event");
my_kbe = (DWORD)(my_keybd_event);
addr = (DWORD*)(0x01bb5000);
VirtualProtect(addr, 4, PAGE_READWRITE, NULL);
while(ReadProcessMemory(GetCurrentProcess(), addr, &dat, 4, NULL))
{
if(dat == (DWORD)o_keybd_event)
{
WriteProcessMemory(GetCurrentProcess(), addr, &my_kbe, 4, NULL);
kbe_hkd = TRUE;
}
addr++;
VirtualProtect(addr, 4, PAGE_READWRITE, NULL);
}
The thunk tables seem to be back to back and ReadProcessMemory seems to always fail at the end of them, so the loop does not run too long. Chainfire, does this make sense to you?
JKingDev said:
...
Do I make sense? This is of course targeting WM6.x (wce5). I just need some way to hook calls to keybd_event from all dlls loaded in the current process. Some of those dlls may be in ROM but they need to be hooked too.
Click to expand...
Click to collapse
Using IAT patch to do this is certainly possible but a lengthy process as you'd have to keep track for all dll loads in services.exe and patch each and every dll as it loads. One of the other methods I described may fit better.
JKingDev said:
I like the sound of (3). Why Use (4) instead? How do you find the export table programmatically? If I use this method, as long as my service is loaded first it should work.
Click to expand...
Click to collapse
(3) is actually (IMHO) a very annoying patch to implement. It doesn't easily allow you to patch/unpatch at will. It doesn't cover coredll-internal jumps. The timing/load-order has to be perfect. It requires slightly more memory. And because you have to load it before anything else if you screw something up there's a good chance you'll need a hard-reset to recover (that's a real ***** with testing!). You can get the export table from the e32 structure of the module, though it isn't always easily patched
JKingDev said:
Ok I just tried something and it worked. It seems that these RAM thunk tables are always loaded at 0x01bb5000 for every process. The following code worked:
The thunk tables seem to be back to back and ReadProcessMemory seems to always fail at the end of them, so the loop does not run too long. Chainfire, does this make sense to you?
Click to expand...
Click to collapse
ROM DLLs create a seperate data section in memory for every process it is loaded into, the IAT is also stored there. Note that the addresses / virtual memory are the same across processes, but different physical memory is used for each process (same as data sections for normal DLLs, though those are located at the normal addresses). To figure out where this memory is look at the rwLow and rwHigh members of the PMODULE structure. (actually I'm surprised you found the location without this )
Chainfire said:
ROM DLLs create a seperate data section in memory for every process it is loaded into, the IAT is also stored there. Note that the addresses / virtual memory are the same across processes, but different physical memory is used for each process (same as data sections for normal DLLs, though those are located at the normal addresses). To figure out where this memory is look at the rwLow and rwHigh members of the PMODULE structure. (actually I'm surprised you found the location without this )
Click to expand...
Click to collapse
That is the vital info I needed! Quick question, do I start searching at rwLow and end at rwHigh, or start at rw Low and end at rwLow+rwHigh?
Thanks!
*edit* Answering my own question, start searching at rwLow and end at rwHigh. I was still having problems because my MODULE structure definition is incorrect, but I was able to find where the information I needed was so it doesnt really matter. Thanks so much!!

How do i get folder size rapidly?!

I write a C# app for WindowsMobile.
in order to get a nonrecursive folder size i have this routine:
Code:
static long GetDirectorySize(String path)
{
long size = 0;
String []files = Directory.GetFiles(path);
foreach (String f in files)
{
FileInfo fi = new FileInfo(f);
size += fi.Length;
}
return size;
}
now, my directory (in Storage Card) has about 1000 files that has about 4MB of data alltogether.
the GetDirectorySize takes forever to execute (60 seconds or so) and provide a horribole user expericnce.
executing this in a thread does not help either - i need the response as fast as possibole.
I was wondering if someone could help me figure out how to get folder size (nonrecursive) more rapidly.
in general, i also want to find the older file in the directory and delete it (kid of cache operation). how do i do that without waiting forever to complete?
storing an index file might not be what i'm looking for.
Thanks
I don't know about C#, but in C++ I use GetDiskFreeSpaceEx function, see HERE.
PS,
I think this goes in the Q&A forum?
dgaud007 said:
I use GetDiskFreeSpaceEx function
Click to expand...
Click to collapse
This does not help with Folder size.
My intention is to manage Cache folder and monitor its size and clear out some cached files in case the cache size of the folder is too big.
getting the disk size is not the way to deal with folder size
You can use it for individual folders, as the folder name is the 1st input parameter. I've used at least for \My Documents which is a regular folder and it works. Here is an excerpt from MSDN:
lpDirectoryName [in, optional]
A directory on the disk.
If this parameter is NULL, the function uses the root of the current disk.
If this parameter is a UNC name, it must include a trailing backslash, for example, "\\MyServer\MyShare\".
This parameter does not have to specify the root directory on a disk. The function accepts any directory on a disk.
The calling application must have FILE_LIST_DIRECTORY access rights for this directory.
Click to expand...
Click to collapse
As per MSDN, here is how you implement it in C#:
Code:
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
I tested GetDiskFreeSpaceEx.
- The coredll has to be used instead kernel32dll (for WindowsMobile).
- the TotalBytes returns the SD card size (on which the folder exists)
- the freeBytesForUser equals FreeBytes and returns the free space in the SD card
this does return the folder size.
appreciate further help.
thanks
I double checked and you're right. Looks like you'll have to recurse while adding the individual sizes. I couldn't find an easier method in a brief search in google. Sorry about the confusion!
PS,
checkout this app...
I'm not that much of a C# expert but isn't the 1000 times calling "new" slowing down? I'd try to write a traditional C++ application using simple FindFirstFile and FindNextFile functions and compare speed towards the C# application. If it's faster then you can just build a C++ DLL and PInvoke her. I'm not sure if results are better but at least it's worth a try.
solution found
I managed to resolve this and get a speedy result by replacing with this code.
all the best.
Code:
private static long GetDirectorySize(String path)
{
long size = 0;
[COLOR="DarkGreen"] /* Slow code
String []files = Directory.GetFiles(path);
foreach (String f in files)
{
FileInfo fi = new FileInfo(f);
size += fi.Length;
} */[/COLOR]
DirectoryInfo di = new DirectoryInfo(path);
FileInfo []fi = di.GetFiles();
for (int i = 0; i < fi.Length; i++)
size += fi.Length;
return size;
}
btw: get my app at http://www.logelog.com/utils

[Q] WP7 - Removing an XElement from an XML file

Hi there,
I'm having a big issue, when trying to remove an XElement from an XML file created in IsolatedStorage.
--------------------------------------------------------------------------------------------
Code to CREATE the XML file
Dim File_to_Create As String = "Tracks.xml"
Dim file As XDocument = <?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlnsd="urn:schemas-microsoft-comfficedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Cartridges.xsd" generated="2010-11-23T14:26:55">
<Carts>
<CART_NAME>First</CART_NAME>
<CART_COLOR>White</CART_COLOR>
</Carts>
<Carts>
<CART_NAME>Second</CART_NAME>
<CART_COLOR>Black</CART_COLOR>
</Carts>
</dataroot>
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Try
If isoStore.FileExists(File_to_Create) Then
MessageBox.Show(File_to_Create + " TRUE")
Else
MessageBox.Show(File_to_Create + " FALSE")
Dim oStream As New IsolatedStorageFileStream(File_to_Create, FileMode.Create, isoStore)
Dim writer As New StreamWriter(oStream)
writer.WriteLine(file)
writer.Close()
MessageBox.Show("OK")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'open selected file
Dim isoStream As IsolatedStorageFileStream
isoStream = New IsolatedStorageFileStream(File_to_Create, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore)
Dim XML_File As XDocument = XDocument.Load(isoStream)
Dim Cart_Query As System.Collections.IEnumerable = From query In XML_File.Descendants("Carts") Order By _
CStr(query.Element("CART_NAME")) Descending, CStr(query.Element("CART_NAME"))
Select New Class_Cartridge_Data With {.Cart_Name = CStr(query.Element("CART_NAME")), _
.Cart_Color = CStr(query.Element("CART_COLOR"))}
Me.ListBox_Cartridges.ItemsSource = Cart_Query
isoStore.Dispose()
isoStream.Close()
End Try
--------------------------------------------------------------------------------------------
Code to ADD / EDIT XElement
Dim File_to_Create As String = "Tracks.xml"
Dim XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
' Check that the file exists if not create it
If Not (XML_IsolatedStorage.FileExists(File_to_Create)) Then
Return
End If
Dim XML_StreamReader As New StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read))
Dim XML_Document As XDocument = XDocument.Parse(XML_StreamReader.ReadToEnd())
XML_StreamReader.Close()
' Update the element if it exist or create it if it doesn't
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c) c.Element("CART_NAME").Value.Equals("First")).FirstOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' Add new
Dim newProgress As New XElement("Cartridges", New XElement("CART_NAME", "Fourth"), New XElement("CART_COLOR", "Blue"))
Dim rootNode As XElement = XML_Document.Root
rootNode.Add(newProgress)
End If
Using XML_StreamWriter As New StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write))
XML_StreamWriter.Write(XML_Document.ToString())
XML_StreamWriter.Close()
End Using
--------------------------------------------------------------------------------------------
Now my issue and request for some help!
If I use
XML_XElement.Remove
then the following exception is raised whenever I try to "refresh" the bounded ListBox
System.Xml.XmlException was unhandled
LineNumber=37
LinePosition=12
Message=Data at the root level is invalid. Line 37, position 12.
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream)
at ListBox_Data_from_XML_LINQ.MainPage.Button_Create_XML_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
InnerException:
--------------------------------------------------------------------------------------------
In short, I can add or edit, but cannot DELETE an XElement...
Any ideas?
Thanks in advance!
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Ren13B said:
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Click to expand...
Click to collapse
Well, I did nothing special, just the XML_Element.remove, instead of adding a new xelement.
Then the error raises whenever I try to reopen the XML file.
My point is, how can I delete an specific xelement?
As far as I know, the following code should work
Code:
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c ) c.Element("CART_NAME").Value.Equals("First")).Firs tOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' remove the selected record
XML_XElement.Remove
End If
Honestly I don't know if the foregoing code is correct or if the issue is related to how WP7 handles the removal thus corrupting the original file.
Please let me know if you need anything else.
Any help is very appreciated!
PS: Thanks for the other replies, helped a lot!
Here's how I did it in c#. My xml file is very different than yours so the query will be different but the important parts are where you load and close the file streams and then write.
Code:
//Get users private store info
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
//open selected file
isoStream = new IsolatedStorageFileStream(list, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
isoStream.Close();
//Find section
XElement sectionElement = xml.Descendants("section").Where(c => c.Attribute("name").Value.Equals(groupn)).FirstOrDefault();
//Find item and remove it
sectionElement.Elements("setting").Where(c => c.Attribute("name").Value.Equals(litem)).FirstOrDefault().Remove();
isoStream.Close(); //Seems unnecessary but it's needed.
//Write xml file
isoStream = new IsolatedStorageFileStream(list, FileMode.Create, FileAccess.Write, isoStore);
xml.Save(isoStream);
isoStream.Close();
Thanks again for your help, greatly appreciated.
However I'm still getting the same error.
Sorry for asking, but are you getting any errors when deleting in WP7 ?
My knowledge on XML is extremely new and I'm sure that I'm making some mistakes somewhere...
But so far, I cannot get past the same exception.
Seems that the XML gots "corrupted" after the delete operation.
On the other hand, if is not too much to ask for, using my current code, how will handle the delete of the selected record?
Thanks!
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Problem is my country is not listed so I cannot register...
Here is the C# version of my current code for adding/editing
Code:
public static void ADD_XML_Record()
{
string File_to_Create = "Tracks.xml";
var XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// Check that the file exists if not create it
if (! (XML_IsolatedStorage.FileExists(File_to_Create)))
{
return;
}
StreamReader XML_StreamReader = new StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read));
XDocument XML_Document = XDocument.Parse(XML_StreamReader.ReadToEnd());
XML_StreamReader.Close();
// Update the element if it exist or create it if it doesn't
XElement XML_XElement = XML_Document.Descendants("Carts").Where((c) => c.Element["CART_NAME"].Value.Equals("dd")).FirstOrDefault();
if (XML_XElement != null)
{
XML_XElement.SetElementValue("CART_NAME", "bbbbb");
}
else
{
// Add new
XElement newProgress = new XElement("Carts", new XElement("CART_NAME", "dd"), new XElement("CART_COLOR", "ff"));
XElement rootNode = XML_Document.Root;
rootNode.Add(newProgress);
}
using (StreamWriter XML_StreamWriter = new StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write)))
{
XML_StreamWriter.Write(XML_Document.ToString());
XML_StreamWriter.Close();
}
}
I tried your code but I'm having a bad time making it to work.
If not a big deal, please could you tell me how to modify it ?
I mean, if a record is found, instead of editing, to remove it?
Honestly I'm stuck and any help is more than apprecisted!
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Ren,
Just to say thank you for your last code. I made a little mod and now it works ok!
Thanks a lot for helping me out!

Possibility to execute download mode programmatically on Omnia 7?

Us T-Mobile users cannot flash Roms at the minute because the download mode button combo has been disabled.
Maybe there is a way to do this programatically or use a resistor accross certain USB pins like the Galaxy S method.
What's your opinion on this?
Sent from my OMNIA7 using Board Express
Yesterday I wasted some time playing around with the USB diagnostic port (enable in the Diagnosis app, it's the third USB mode option). Both PSAS and QPST can connect to and mess with the phone, so I think if someone knows his way around, the phone can be kicked into Download Mode.
(I only managed to crash the phone in many different ways, but I was really just monkeying around.)
If this can be done it would be great as this is the first phone I have owned where I cannot flash firmware myself.
Might be worth while seeing if everyone with a tmobile uk branded omnia 7 has this issue?
FYI I have included my firmware versions etc so we can try and collate a list of working/non working ones to see what the differences are if any.
os version 7.0.7004.0
firmware revision number 2424.10.10.6
hardware revision number 3.15.0.4
radio software version 2424.10.10.6
radio hardware version 0.0.0.800
bootloader version 4.10.1.9
chip soc version 0.36.2.0
KarmaXXK said:
Yesterday I wasted some time playing around with the USB diagnostic port (enable in the Diagnosis app, it's the third USB mode option). Both PSAS and QPST can connect to and mess with the phone, so I think if someone knows his way around, the phone can be kicked into Download Mode.
(I only managed to crash the phone in many different ways, but I was really just monkeying around.)
Click to expand...
Click to collapse
Yes, I tried the *#7284# code and changed the USB Path Control to "Modem, USB Diag" and my phone was recognised by the ROM Downloader but the phone was not in download mode.
I have stumbled upon something which may be what we are looking for though, after reverse engineering the Samsung Diagnosis app I notice there are codes to access 'Operator Specific' Admin areas in the app. Take a look at the attached image.
Now as you can see, the values listed cannot be typed into the Diagnosis app as there is a formula to decipher them. I have the formula but cannot get it to work.
Code:
Private Overloads Function GetHashCode(ByVal str As String) As UInteger
Dim num As UInteger = 0
For i As Integer = 0 To str.Length - 1
[B]num = ((num << 5) + num) + str(i)[/B]
Next
Return num
End Function
Now the bit highlighted in bold is the bit I cant get to work.
It gives the following error:
Operator '+' is not defined for types 'UInteger' and 'Char'.
Once someone can help to get this working, reversing the formula should in theory show us the correct *#000# code combination for each area.
Fingers crossed you can crack it!
lyriquidperfection said:
Yes, I tried the *#7284# code and changed the USB Path Control to "Modem, USB Diag" and my phone was recognised by the ROM Downloader but the phone was not in download mode.
I have stumbled upon something which may be what we are looking for though, after reverse engineering the Samsung Diagnosis app I notice there are codes to access 'Operator Specific' Admin areas in the app. Take a look at the attached image.
Now as you can see, the values listed cannot be typed into the Diagnosis app as there is a formula to decipher them. I have the formula but cannot get it to work.
Code:
Private Overloads Function GetHashCode(ByVal str As String) As UInteger
Dim num As UInteger = 0
For i As Integer = 0 To str.Length - 1
[B]num = ((num << 5) + num) + str(i)[/B]
Next
Return num
End Function
Now the bit highlighted in bold is the bit I cant get to work.
It gives the following error:
Operator '+' is not defined for types 'UInteger' and 'Char'.
Once someone can help to get this working, reversing the formula should in theory show us the correct *#000# code combination for each area.
Click to expand...
Click to collapse
I worked on this few days ago, I couldn't reverse the hash function but we had some brilliant ideas how to do it (see the stackoverflow thread about it http://stackoverflow.com/questions/4523553/reversing-a-hash-function)
but I used brute force and extracted some 60 diagnosis codes that you can find here http://www.martani.net/2010/12/windows-7-hacks-all-diagnosis-codes-you.html
and here http://www.martani.net/2010/12/windows-7-hacks-all-diagnosis-codes-you_26.html
This is great stuff martani if there is any way to decipher these ones, they may be worth looking at:
g_ADMIN_GENERIC = 3370684588
g_ADMIN_TMOBILE = 469486183
g_ADMIN_VODAFONE = 474092301
These ones indeed look very interesting and may offer a way to enable ADC or even the Download Mode some people like me have been looking for.
lyriquidperfection said:
This is great stuff martani if there is any way to decipher these ones, they may be worth looking at:
g_ADMIN_GENERIC = 3370684588
g_ADMIN_TMOBILE = 469486183
g_ADMIN_VODAFONE = 474092301
These ones indeed look very interesting and may offer a way to enable ADC or even the Download Mode some people like me have been looking for.
Click to expand...
Click to collapse
Actually the code is a little misleading, if you see closely, the enum HashCodeTable is used nowhere.
The app waits for user input, after each "tap" on a number it calls the function ParseDial() that hashes the input with GetHashCode then calls the function GetEnumFromList() on this hashed value.
In GetEnumFromList, there is no use of HashCodeTable and even the codes you provided are not hard-coded in this function. I am not sure why they are there but as far as I can tell, to access these parts of the diagnosis app, you need another method than dialing a code it seems
martani said:
Actually the code is a little misleading, if you see closely, the enum HashCodeTable is used nowhere.
The app waits for user input, after each "tap" on a number it calls the function ParseDial() that hashes the input with GetHashCode then calls the function GetEnumFromList() on this hashed value.
In GetEnumFromList, there is no use of HashCodeTable and even the codes you provided are not hard-coded in this function. I am not sure why they are there but as far as I can tell, to access these parts of the diagnosis app, you need another method than dialing a code it seems
Click to expand...
Click to collapse
Damn it! Looks like we are back to square one!
Have you seen also on the Samsung Galaxy S the Download mode is disabled on some devices, but some users made a jig where you bridge 2 pins with a certain resistor and it knocks the phone into download mode. Maybe this would work on the Omnia 7 also????
I am hoping for a software based fix rather than hacking together something.
**ALL** diagnostic codes for SAMSUNG devices
I reverse engineered the Diagnostic Menu Application. It contains a list of configuration "Titles" with corresponding hash-codes. I made a tool to reverse the hash-codes to dial-codes. The dial-codes may not be the same as some codes that were already known, but the dial-codes are absolutely correct for these menu. Differences are due to hash-collisions (same hash-code may have multiple possible dial-codes). I just used the shortest dial-codes for every menu.
The list of menu's is very long and I discovered that not all menu-codes were not actually implemented. I guess this list of codes is used for all Samsung devices (possibly also for Galaxy S and older Windows Mobile devices). So not all dial-codes may actually work on your device.
WARNING!! The menu's can configure low-level settings of your phone. And if you don't know what you're doing you may brick your device or maybe hard-reset the device and loose all your data and settings. Or you may faulty calibrate your sensors. Be very, very careful with experimenting!! I will not take any responsibility for damaging your device in any way.
I would personally be very interested if anyone finds a way to get the device in download-mode by using these menu's (I have a bad bootloader which does not let my Samsung Omnia 7 go into download-mode to flash it to a newer firmware).
By the way: the admin menu's are NOT implemented on the Omnia 7 :-(
This is the list with menu-titles, dial-codes and their hashcode:
Code:
FTAMain = 15 (0x686)
QUALCOMM TEST = *09# (0x17DB96)
TMOServiceMenu = *74*# (0x31710C2)
SMDINFO = *#03# (0x30C0953)
SIMPLE FUNCTION TEST = *#05# (0x30C0995)
IMEI NUMBER = *#06# (0x30C09B6)
VIEWHISTORYNW = *#07# (0x30C09D7)
LCDTEST = *#0*# (0x30C082A)
QWERTYTEST = *#1*# (0x30C0C6B)
BATT TEST = *#2*# (0x30C10AC)
BRIGHTNESS TEST = *#3*# (0x30C14ED)
TouchDelta 80 = *#80# (0x30C2AF8)
LIGHTTEST = *#12*# (0x648DBCDD)
BTLOGDUMP = *#232# (0x648E4E87)
WIFI FACTORY TEST = *#526# (0x648FEFED)
RILNETLOG = *#638# (0x649080D1)
RILDUMP = *#745# (0x64911110)
VPHONE770 = *#770# (0x64911D2E)
VPHONE771 = *#771# (0x64911D4F)
VPHONE772 = *#772# (0x64911D70)
VPHONE773 = *#773# (0x64911D91)
VPHONE774 = *#774# (0x64911DB2)
VPHONE775 = *#775# (0x64911DD3)
VPHONE776 = *#776# (0x64911DF4)
VPHONE777 = *#777# (0x64911E15)
VPHONE778 = *#778# (0x64911E36)
VPHONE779 = *#779# (0x64911E57)
SR TEST = *#780# (0x6491216F)
VT DUMP = *#938# (0x649225F4)
Disable Testbed = #12358# (0xFC28BE89)
Enable Testbed = *12358# (0x170067D0)
DEBUGMODE1 = *#0011# (0xF63246F2)
BATTERYINFO = *#0228# (0xF63364DC)
PHONELOOPBACKTEST = *#0283# (0xF6337DBD)
AUDIOTEST2 = *#0289# (0xF6337E83)
FMRADIORX = *#0368# (0xF6340241)
LIGHTSENSORTEST = *#0589# (0xF63523A6)
RRCVERSION = *#0599# (0xF63527E7)
AUDIOTEST = *#0673# (0xF635AB00)
SOUNDTEST = *#0675# (0xF635AB42)
RTC = *#0782# (0xF6363B81)
DEVICETEST = *#0842# (0xF636B6DE)
ILLUMINATIONTEST = *#0843# (0xF636B6FF)
MultiTouch = *#0987# (0xF63754E8)
SWversionFTA = *#1111# (0xF644EBD4)
MOUSETEST = *#121*# (0xF645774E)
SWversionEx = *#1234# (0xF645811A)
MOUSECAL = *#123*# (0xF6457FD0)
MOUSECAL06 = *#126*# (0xF6458C93)
GPSTEST = *#1575# (0xF6473762)
MICROUSB TEST = *#1793# (0xF6485864)
HWversionFTA = *#2222# (0xF6579518)
BANDSELECTION = *#2263# (0xF657A63D)
PHONEDUMP = *#2454# (0xF658BADF)
CAMERAUPDATE = *#2470# (0xF658C2DD)
CAMERADISABLE = *#2480# (0xF658C71E)
NAVIKEY TEST = *#2486# (0xF658C7E4)
INTEGRITY = *#2580# (0xF659537F)
TouchFirmare 2663 = *#2663# (0xF659D7C1)
TouchDelta 2664 = *#2664# (0xF659D7E2)
TouchDelta 2665 = *#2665# (0xF659D803)
RILNETLOG OFF = *#6380# (0xF6A09CC1)
RILNETLOG ON = *#6381# (0xF6A09CE2)
NETLOCK NETWORK = *#6955# (0xF6A3DAE9)
USBPATHCHANGE = *#7284# (0xF6B22965)
POWERONATTACH = *#7298# (0xF6B22E2A)
SELF DIAGNOSTIC MODE = *#7353# (0xF6B2A8E2)
DebugOption = *#7450# (0xF6B334E0)
ERROR REPORT ON = *#7451# (0xF6B33501)
ERROR REPORT VERIFY = *#7452# (0xF6B33522)
NETLOCK SERVICE = *#7755# (0xF6B4DAA8)
VPHONE DISABLED = *#77*0# (0xF6B4AB38)
VPHONE ENABLED = *#77*1# (0xF6B4AB59)
UARTCHANGER = *#9090# (0xF6D54562)
DEBUGDUMP = *#9900# (0xF6DA0E82)
PILEDUMP = *#9901# (0xF6DA0EA3)
NETLOG LOG START = *#9905# (0xF6DA0F27)
DEBUG RIL DUMP = *#9906# (0xF6DA0F48)
ERRORREPCAB INSTALL = *#9907# (0xF6DA0F69)
GUMITEST3G CAB INSTALL = *#9908# (0xF6DA0F8A)
SUWON3G CAB INSTALL = *#9909# (0xF6DA0FAB)
UARTPATH = *#9910# (0xF6DA12C3)
BATTERYMONITOR = *#9911# (0xF6DA12E4)
CONNECTION SETTING = *#9920# (0xF6DA1704)
VERIFYCOMPARE = *#9990# (0xF6DA34CB)
YSSHINTEST = *#9999# (0xF6DA35F4)
VersionScript = 19104#2* (0xD21FC43E)
BLUETOOTH LOG DISABLE = 20652609 (0x1598F3DE)
BLUETOOTH LOG ENABLE = 20652619 (0x1598F3FF)
BT SSPDEbugModeEnable = 20652629 (0x1598F420)
BT SSPDEbugModeDisable = 20652639 (0x1598F441)
OMADMCLIENT LOG DISABLE = 20653609 (0x1599803F)
OMADMCLIENT LOG ENABLE = 20653619 (0x15998060)
CELOG LOG DISABLE = 20654609 (0x159A0CA0)
CELOG LOG ENABLE = 20654619 (0x159A0CC1)
TOTALCALLTIME = 2934331* (0xC35403F3)
RESET CUSTOM = 35180948 (0x77496B66)
RESET FACTORY = 35190718 (0x775B7B02)
ERASE IMEIITEM = 35190728 (0x775B7B23)
IMEI ADJUST = 35190738 (0x775B7B44)
BLUETOOTH RF TEST = 3##65*88 (0xECE73A9E)
BLUETOOTH AUDIO TEST = 3##65*98 (0xECE73ABF)
AutoSimSetting = 40*047#3 (0xD1C556DF)
PVKKey = 40*549#3 (0xD21FD9E6)
RESET FACTORY WITHDEFAULTLANGUAGE = 76264513 (0x777E1362)
NONSLEEPCALL OFF = *#069*0# (0xBCEBFF49)
NONSLEEPCALL ON = *#069*1# (0xBCEBFF6A)
LEDTEST = *#14789# (0xBF1C1ADD)
DMSessionInit = *#15428# (0xBF2C7494)
CIPHERING = *#32489# (0xC3A095FA)
CAMERAUPDATESVC = *#32589# (0xC3A1225B)
LOGDUMPMGR = *#33284# (0xC3B19514)
SR DISABLED = *#780*0# (0xCD5F5D49)
SR ENABLED = *#780*1# (0xCD5F5D6A)
NETLOCK SUBSET = *#78255# (0xCD60A57B)
LAUNCH UAEDIT = *#92782# (0xD1A12DFC)
PdaBuildTime = *#99820# (0xD2204C1C)
VersionTime = *#99821# (0xD2204C3D)
WIFI TEST = 0373385#6 (0xECE73BA6)
EN LOCK NW = 074578132 (0xBBF27D35)
GCFTESTMODE ENTER = 086#58023 (0x1807BAE3)
FILE SYSTEM TEST = 089559715 (0x28F3F681)
AUDIOGAINCONTROL = 08#766104 (0x902D68E3)
DIS LOCK SUB NW = 17#991#3* (0x1D45A6AE)
PVKFileName = 18*357#25 (0x161B193C)
EN LOCK SUB NW = 193582504 (0xBC073A15)
GPSTESTTOOL = 1#8865#55 (0xF61EC09C)
EN LOCK CORP = 1*0273411 (0xF62C007D)
EN LOCK SVC = 1*0278411 (0xF62EBE62)
DIS LOCK NW = 20789802* (0x1D30E9CE)
SellOutSMS = 2615#0922 (0xD04CA8DE)
TFlashUnPairing = 30334*733 (0x51B892C4)
DIS LOCK SVC = 38025*93# (0xCA957BDB)
GPSTESTTOOL2 = 400#40*08 (0xB9F6D60D)
GPSTESTXTRA = 400#40*18 (0xB9F6D62E)
SerialNumber = 5317*0648 (0x6E256D8C)
EN LOCK SIM = 5494585*3 (0xBC051995)
SERVERURL = 553378683 (0xD8389060)
SLIDECOUNT = 584644021 (0xF0BF3052)
SellOutSMSTestMode = 597#*224# (0x96E7B26D)
APPSLAUNCHER = 5**6244*3 (0x33B0B76)
SLOGSERIAL M2 = 66#6757#1 (0x7050E07C)
AutoReceive Enable = 7160*5088 (0xEF2C5E0D)
TESTMODE = 718071#49 (0x8A09ACC8)
RESET SERVICE = 72673#00# (0xEC5B4BEF)
ReactivateSellOutSMS = 74201#086 (0x807DB65F)
AUDIOCODEC = 7#16#1#37 (0x902D68C2)
ADMIN GENERIC = 838*5448* (0xC8E890AC)
SLOGSERIAL ALL ON = 8644*3081 (0x705107AC)
VT MANUALSETTING = 8802*7*5# (0x104384B5)
DISLOCK SIM = 98217*243 (0x1D43862E)
DMTESTMENU = 9#7357764 (0x414D9633)
SLOGSERIAL ALL OFF = #22#6214# (0x7050E03A)
SLOGSERIAL M1 = #22#6215# (0x7050E05B)
SLOGSERIAL M3 = #22#6217# (0x7050E09D)
SLOGSERIAL M4 = #22#6218# (0x7050E0BE)
SLOGSERIAL M5 = #22#6219# (0x7050E0DF)
ADMIN VODAFONE = #75471648 (0x1C42130D)
DisableSellOutSMS = *4587*676 (0x903477AF)
BLUETOOTH SEARCH TEST = *#232333# (0xECE73AE0)
RANDOM BT MAC = *#232336# (0xECE73B43)
BLUETOOTH MAC VIEWER = *#232337# (0xECE73B64)
WIFI MAC VIEWER = *#232338# (0xECE73B85)
PRECONFIGURATION = *#638738# (0x213EF313)
SELF DIAGNOSTIC MODE DISABLE = *#7353*0# (0x6E008D7C)
SLOGSERIAL M6 = *#745*06# (0x7050E100)
DIS LOCK CORP = 00*2*2#524 (0xCA92BDF6)
ADMIN TMOBILE = 0612824763 (0x1BFBCA67)
AutoReceive Disable = 09925572#3 (0xD4B8217D)
SWversionIn = 1309653522 (0xECB23FC4)
GPSTTFFTESTTOOL = 154*068271 (0xF61EBC7C)
SellOutSMSProductionMode = 1#3341#5#0 (0x96D7C68A)
LOCK STATUS INFO = 28##**23*0 (0x7D8C72E3)
SWversionNewIn = 32456464#7 (0xFD58D7FC)
Heathcliff74 said:
I reverse engineered the Diagnostic Menu Application. It contains a list of configuration "Titles" with corresponding hash-codes. I made a tool to reverse the hash-codes to dial-codes. The dial-codes may not be the same as some codes that were already known, but the dial-codes are absolutely correct for these menu. Differences are due to hash-collisions (same hash-code may have multiple possible dial-codes). I just used the shortest dial-codes for every menu.
Click to expand...
Click to collapse
Can you share how did you reverse the hash function? I worked on this some time ago but finally just brute forced it to extract the keys.
I would also like to know how he reversed the hash codes! I tried for hours and had no luck!
Haha.. Well, I first tried to calculate the original dial-codes, but that seems to work only for dialcodes shorter than 8 digits (5 bits per digit, 32 bits hash-code = 32 / 5 = 7 digits + 1 digit for the extra add):
Code:
uint hash = 0; // enter hash here
string DialCode = "";
while (hash > 0)
{
uint digit = (hash % 33) + 33;
if (digit > hash)
hash = 0;
else
hash = (hash - digit) / 33;
DialCode = Convert.ToChar(digit) + DialCode;
}
return DialCode;
But this does not work for long dial-codes. So after that I just made a little program to brute-force it. I copied the enum with menu-titles and hash-codes to my project. Then I used reflection to populate a sortedlist. Then I started to brute-force and check all dialcodes for their hashcode and see if it exists in the list. If it exists, I add it to a textbox and remove the item from the list. That's it. So it is not really reversed, but my program took about an hour to get dial-codes for all the hashcodes in the enum.
Code:
SortedList<uint, string> hashCodes = new SortedList<uint, string>();
int l = typeof(HashCodeTable).GetEnumNames().Length;
string[] menunames = typeof(HashCodeTable).GetEnumNames();
for (int i = 0; i < l; i++)
{
try
{
hashCodes.Add(Convert.ToUInt32(Enum.Parse(typeof(HashCodeTable), menunames[i])), menunames[i].Substring(2).Replace('_', ' '));
}
catch { }
}
char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '#', '*' };
for (int length = 1; length <= 20; length++)
{
ushort[] digits = new ushort[length];
for (int i = 0; i < length; i++) digits[i] = 0;
while (true)
{
// calc hash
uint hashCode = 0;
for (int i = 0; i < length; i++)
{
hashCode = ((hashCode << 5) + hashCode) + chars[digits[i]];
}
if (hashCodes.ContainsKey(hashCode))
{
int m = hashCodes.IndexOfKey(hashCode);
string str = "";
for (int j = 0; j < length; j++)
str = str + chars[digits[j]];
textBox1.Text = textBox1.Text + hashCodes.Values[m] + " = " + str + " (0x" + hashCode.ToString("X") + ")" + Environment.NewLine;
hashCodes.RemoveAt(m);
}
// increase
digits[length - 1]++;
for (int k = length - 1; k >= 0; k--)
{
if (digits[k] >= 12)
{
if (k == 0)
break;
else
{
digits[k] -= 12;
digits[k - 1]++;
}
}
}
if ((digits[0] >= 12) || (hashCodes.Count == 0)) break;
}
if (hashCodes.Count == 0) break;
}
Excellent stuff! Thank you for this very interesting code snippit!
WP7 diag codes
martani said:
Actually the code is a little misleading, if you see closely, the enum HashCodeTable is used nowhere.
Click to expand...
Click to collapse
This is because the compiler optimized out the switch statement and compiled the constants into the IL code for the hash codes.
Within the main switch statement where keypad entries are evaluated there are ~112 codes and I've reversed all of them. Writing hash algorithms is not straightforward and it's quite a simple one, since my app captured 2-3-4 variants of keycodes for the same hash value.
Regarding the most interesting entries at the top of the enum the ADMIN_ entries...those hash values are not handled by the application, maybe Samsung has another diag app or a different app which is using the same method.
The other thing I can think of is there are APIs in the diag app which one is sending the hash of a keycode to the given driver...I tried that but the ADMIN stuff did not worked that way either :-((
If anyone is interested I can post the resolved codes, but not sure if I can post it in the forum or not ;-)
Regsitry entry to enable SLDR mode
I found this definition in B44C7A84-5068-4b43-A1E5-F870A80F6FF8.rgu:
[HKEY_LOCAL_MACHINE\Drivers\BuiltIn\UsbFn]
...
"OsMode"=dword:0 ; 0 for Main OS, 1 for SLDR
....
Is the download mode == SLDR mode?
Since maybe we can set this entry "somehow", and upon next reboot we will get into download mode so we can flash the device?
So the question is, what is SLDR mode? Secure Loader mode? I don't know this, a more pro in this area should help out ;-)
UPDATE
I was able to read the value (0) and write it back (0). Did not tried to write 1 there
Hey guys. I know this thread is about programmatically enter downloadmode, but I wanted to try the 301k resistor trick and I can confirm it works on Samsung Omnia 7.
I used this guide. If you're gonna do that too, then you should pay attention to these things:
- The guide refers to pin 4 and 5 being closest to the headphone socket. But on the omnia 7, the headphone and micro-usb sockets are the other way around if you compare it to the Galaxy S. The guide is for the Galaxy S, so you should really pay attention to which pins you solder the resistor(s). This is the best picture on how you should solder the resistor(s).
- Many micro-usb cables have no wire for pin 4. Some connectors don't even have a pin 4. You should first verify that your connector has all 5 pins. If you only have 4 wires, then you have to dismantle the connector and solder directly on the back of the connector.
I switched off my Omnia 7. I plugged in my jig and it went to downloadmode immediately.
It's late now, so I will see tomorrow what I will be going to flash on it. There quite a few roms and I'm not sure which one I should use. I have to figure that out first.
If anyone has questions about how to make a jig, just ask. I know how to make one now.
You should post pictures, how to make such a cable. Thanks
FromOuterSpace said:
You should post pictures, how to make such a cable. Thanks
Click to expand...
Click to collapse
The picture I linked to in my previous post look pretty clear to me. It shows what pins you have to use. The guide I linked to contain all the other necessary details. If you have any specific questions about something that is still not clear, you can ask me.

[Q] Coding in Error checking for VB.net CF app

Hello all, Sorry for the dumb question but i'm pretty new to VB.Net CF.
I'm working on a little program that exports settings from the registry and then writes to the SD card for XDA_UC to import when a new rom installed. I'm currently struggling with the error checking code. I want it to be able to tell if there was an issue updating an already existing file with new settings but i can't seem to find a way to do it. I have managed to get it to check the file was written but this only works the first time. After that it always reports a success if the file is present in the expected location.
I've pated what i have below. I appreciate all and any thoughts you may have.
Code:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Private[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdent_Click([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sender [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] System.Object, [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] e [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] System.EventArgs) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Handles[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdent.Click[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Setup The variables so we can have them ready to write the .reg file[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] BTIdentity [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] = Registry.GetValue([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"HKEY_LOCAL_MACHINE\Software\WIDCOMM\BTConfig\General"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"DeviceName"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2], 0)[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sw [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] IO.StreamWriter = IO.File.CreateText([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\BT_Ident.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Format and then write the reg file to disk[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Windows Registry Editor Version 5.00"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.WriteLine()[/SIZE]
[SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"[HKEY_LOCAL_MACHINE\Software\WIDCOMM\BTConfig\General]"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.WriteLine([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"""DeviceName""="""[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] + BTIdentity.ToString + [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]""""[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2]sw.Flush()[/SIZE]
[SIZE=2]sw.Close()[/SIZE]
[SIZE=2][COLOR=#008000][SIZE=2][COLOR=#008000]'Check that the file wrote successfully (this needs work becuase it will always report "operation successful" once the file has been written once[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] File.Exists([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\BT_Ident.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]MessageBox.Show([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Operation Complete."[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Else[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]MessageBox.Show([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"Operation Failed."[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][/COLOR][/SIZE]
[/COLOR][/SIZE][/COLOR][/SIZE]
You could use FileSystemInfo properties of the file to make sure it was actually updated.
Code:
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\BT_Ident.reg")
This will reveal the FileSystemInfo properties of the file, as defined here:
http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo_members(v=VS.71).aspx
LastWriteTime is the last time the file was written to. If it wasn't within the last few seconds then the update has failed.
I've got to a point in my project where i actually need to look at doing this so thanks for taking the time to post.
this i what i've come up with so far
Code:
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]File.Exists([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\VolumeTest.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]) [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fsi [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] FileSystemInfo = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] FileInfo([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"\Storage Card\XDA_UC\volumetest.reg"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fsi.LastWriteTime = DateAndTime.Now [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]OpComplete()[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]Else[/COLOR][/SIZE]
[/COLOR][/SIZE][SIZE=2]OpFailed()[/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]End If[/COLOR][/SIZE][/COLOR][/SIZE]
It should work but i would like to say dateandtime.now +/- say 5 seconds and i'm having trouble figuring that part out.
Any ideas?
This should do the trick.....
Code:
Dim Seconds5 As New TimeSpan(0,0,5)
If File.Exists("\Storage Card\XDA_UC\VolumeTest.reg") Then
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\volumetest.reg")
If (DateAndTime.Now - fsi.LastWriteTime) < Seconds5 Then
OpComplete()
Else
OpFailed()
End If
End If
Alternatively, drop line 1 and put it straight into the compare, as that what the compiler will do anyway, when you switch it to a 'Release' build.
Code:
If File.Exists("\Storage Card\XDA_UC\VolumeTest.reg") Then
Dim fsi As FileSystemInfo = New FileInfo("\Storage Card\XDA_UC\volumetest.reg")
If (DateAndTime.Now - fsi.LastWriteTime) < New TimeSpan(0,0,5) Then
OpComplete()
Else
OpFailed()
End If
End If
Cool, thanks. I really do appreciate you taking the time to help.

Categories

Resources