ラベル 开发技巧 の投稿を表示しています。 すべての投稿を表示
ラベル 开发技巧 の投稿を表示しています。 すべての投稿を表示

2007年2月14日水曜日

怎样在程序中支持多国语言

文章原始出处 http://lunatic.bokee.com

介绍
本文介绍如果在程序中支持多国语言,并实现动态切换。

读者评分 3 评分次数 1

正文
本文以emule为例,探讨一下多国语言支持的实现。选择emule,因为它的多国语言支持实现的相当好,可以支持动态切换。而且最关键,它是开源的,可以直接通过源码来研究它的实现技术。

   emule是利用动态加载资源DLL来实现多语言切换的,每一个资源DLL中包含了一份对应某一语言的字符串表。在源码的srchybrid\lang 路径上可以发现一个lang解决方案,其中包含了差不多40个项目,每个项目编译出来都是一个单独的DLL。这些DLL在程序安装时拷贝到指定的目录中。 每个DLL里面都是一个大的string table。emule为每一个用到的字符串(大约为1400多个)都指定了一个固定ID,在不同的DLL中这个ID对应了这个字符串的不同语言的翻译版 本。这样每当需要这个字串时就通过ID去获取,在当时程序加载的某一特定语言的DLL,就可以取到相应语言的字串。
  英文版本的string table编译在主EXE文件中,这样当某一语言不支持,或DLL文件加载失败时还可以使用英语版本。

  下面我们就看看具体的实现。

   主要实现代码在I18n.cpp文件中。入口函数是 void CPreferences::SetLanguage() ,这个函数在在 void CPreferences::LoadPreferences() 函数中被调用,即载入了程序的各种选项后。当程序第一次运行时,在选项文件(即 preferences.ini)中没有内容,SetLanguage函数会根据系统的本地语言设置来加载对应的语言DLL资源,所以我们第一次安装后就 是中文,无需设置。这一点我们后面会说到。
  另外在 BOOL CPPgGeneral::OnApply() 中也调用了该函数,即用户在“选项”窗口中改变了语言选择后。

   在 void CPreferences::SetLanguage() 函数中,首先调用了 static void InitLanguages(const CString& rstrLangDir, bool bReInit = false) 函数。这个函数主要是通过遍历“语言”目录(即我们前面说地的,专门用于存放各种语言版本DLL的目录),来初始化静态“语言表” (_aLanguages),这是个静态数组,其中的每一项对应一种支持的语言。凡能找到相应DLL文件的,就在表中标记该语言为支持。
  然后 调用 static bool LoadLangLib(const CString& rstrLangDir, LANGID lid) 来载入相应的语言DLL。这个函数比较简单,通过查“语言表”(_aLanguages),如果要载入的语言是支持的,就加载相应的DLL文 件,并将DLL模块句柄存到_hLangDLL中,这也是一个静态变量。我们可以看到如果是英语,是不需要加载的,直接用EXE模块中的资源字符串表。
  如果调用LoadLangLib文件加载指定的语言失败,程序会尝试判断本地系统的语言集,并加载对应的语言,如果加载也失败就使用英语。
  语言文件加载成功后,程序会尝试从中加载一个字串,如果失败,说明可能DLL文件损坏,则再重设语言为英语。英语字串是内置在EXE文件中的,所以是最可靠的。
  至此,加载成功,句柄保存在_hLangDLL静态变量中。

   最后在需要字符串的地方程序通过 CString GetResString(UINT uStringID, WORD wLanguageID) 或 CString GetResString(UINT uStringID) 函数加载相应的字符串。这个函数的功能很简单,就是从_hLangDLL指定的模块中加载字符串资源。如果_hLangDLL为 NULL就是从当前模块加载,我们前面已经看到了,如果使用英语这个变量的值就是NULL。
  在emule的源码中,几乎每个对话框都实现了一 个Localize(void)函数,这个函数就是通过调用GetResString来设置对话框上所有控件的文字。在  BOOL CPPgGeneral::OnApply() 函数中我们可以看到,在调用CPreferences::SetLanguage函数切换了语言后,会依 次调用对话框和窗口的Localize(void)函数,重新设置UI的文字内容。

  最后注意一点,如果你想让应用支持多语言,在设计对话框时要把对话框的Language属性设为“非特定语言”。在“资源”视图中选中相应的对话框节点,再切换到“属性”视图就可以看到这个选项了。如果不设置会出现乱码。

2007年1月19日金曜日

Sorting a Column in a JTable Component

This example implements a method that sorts the data of a particular column of a DefaultTableModel.

DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);

// Add data here...

// Disable autoCreateColumnsFromModel otherwise all the column customizations
// and adjustments will be lost when the model data is sorted
table.setAutoCreateColumnsFromModel(false);

// Sort the values in the second column of the model
// in descending order
int mColIndex = 1;
boolean ascending = false;
sortColumn(model, mColIndex, ascending);

// Regardless of sort order (ascending or descending), null values always appear last.
// colIndex specifies a column in model.
public void sortColumn(DefaultTableModel model, int colIndex, boolean ascending) {
Vector data = model.getDataVector();
Object[] colData = new Object[model.getRowCount()];

// Copy the column data in an array
for (int i=0; i<colData.length; i++) {
colData[i] = ((Vector)data.get(i)).get(colIndex);
}

// Sort the array of column data
Arrays.sort(colData, new ColumnSorter(ascending));

// Copy the sorted values back into the table model
for (int i=0; i<colData.length; i++) {
((Vector)data.get(i)).set(colIndex, colData[i]);
}
model.fireTableStructureChanged();
}

public class ColumnSorter implements Comparator {
boolean ascending;
ColumnSorter(boolean ascending) {
this.ascending = ascending;
}
public int compare(Object a, Object b) {
// Treat empty strains like nulls
if (a instanceof String && ((String)a).length() == 0) {
a = null;
}
if (b instanceof String && ((String)b).length() == 0) {
b = null;
}

// Sort nulls so they appear last, regardless
// of sort order
if (a == null && b == null) {
return 0;
} else if (a == null) {
return 1;
} else if (b == null) {
return -1;
} else if (a instanceof Comparable) {
if (ascending) {
return ((Comparable)a).compareTo(b);
} else {
return ((Comparable)b).compareTo(a);
}
} else {
if (ascending) {
return a.toString().compareTo(b.toString());
} else {
return b.toString().compareTo(a.toString());
}
}
}
}

2007年1月17日水曜日

如何用applet关闭浏览器窗口及打开一个窗口

1,打开新窗口
Frame n_Win = new Frame();
n_Win .setLocaltion(100,100);
n_Win .setSize(200,200);
n_Win .show();
2,关闭
加个windowListener就可以。

用cos进行文件上传

在jsp中实现文件上传,可用的类库很多,比如有著名的jspsmart公司SmartUpload,struts里面也有。我这里说说cos,它是 O'Reilly公司的,O'Reilly的图书是很8错的,这个上传的组件也做得很棒,最重要的是,它是open source的.

1.下载最新的cos包(http://www.servlets.com/cos/index.html),加入到你的classpath中
2.编写一个需要上传文件的jsp,为了方便,我就用一个简单的htm文件了,在这个页面中,我们让用户一次可以上传3个文件.
/////////////////////upload.htm//////////////////////////////////////
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无h・文档</title>
</head>

<body>
<!-- enctype的<P很重要,upload.jsp:NY理上 O的jsp-->
<form name="form1" method="post" enctype="multipart/form-data" action="upload.jsp">
<p>
<input name="file1" type="file">
</p>
<p>
<input name="file2" type="file">
</p>
<p> <input name="file3" type="file">
</p>
<p>
<input type="submit" name="Submit" value="上 O">
</p>
</form >

</body>
</html>

3.在c:\下建一个目录c:\upload,用来存放上传的文件。

4.写一个jsp或者servlet来实现上传,我这里用一个叫upload.jsp,这样就不用配置web.xml,呵呵,比较懒的说。

////////////////////////////upload.jsp////////////////////////////////////////
1. <%@page import="java.io.*"%>
2. <%@page import="com.oreilly.servlet.MultipartRequest"%>
3. <%@page import="com.oreilly.servlet.multipart.CoverFileRenamePolicy"%>
4. <%@page contentType="text/html; charset=gb2312" %>
5. <%
6. //文件上 O后,保存在c:\\upload
7. String saveDirectory ="c:\\upload";
8. //マk个文件最大5m,最多3个文件,所以...
9. int maxPostSize =3 * 5 * 1024 * 1024 ;
10. //response的x:N"gb2312",同采用缺省的文件名冲突解决策略,杣ーs上 O
11. MultipartRequest multi =
12. new MultipartRequest(request, saveDirectory, maxPostSize,
13. "gb2312");
14.
15. //棟出反・信息
16. Enumeration files = multi.getFileNames();
17. while (files.hasMoreElements()) {
18. System.err.println("ccc");
19. String name = (String)files.nextElement();
20. File f = multi.getFile(name);
21. if(f!=null){
22. String fileName = multi.getFilesystemName(name);
23. String lastFileName= saveDirectory+"\\" + fileName;
24. out.println("上 O的文件:"+lastFileName);
25. out.println("<hr>");
26.
27. }
28. }
29.
30. %>
31. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">

5.最后把这2个文件发布到你的服务器就行了。上传文件就搞定啦,以后你想在你邮件系统里面嵌入发送附件的功能,用这个来做上传也不错啊。

2006年12月24日日曜日

瘦身你的执行文件(VC)

作者:jhkdiy
在网上,有好多绿色软件,不仅功能强大,而且软件本身的体积非常小。有的通常
只在几十K左右。那他们是怎么做到把软件做的怎么小的呢?现在我手把手的告诉
你如何通过修改程序的编译选项来瘦身你的执行文件。

先看一个最典型的程序:

#i nclude <stdio.h>
int main()
{
printf(
"Hello, World! ");
return 0;
}


上面的程序之所以被称之为典型,是因为他有如下的内容:
1、系统函数调用:printf
2、有静态数据段

好,现在把此文件放到VisualStudio6.0中进行编译,看看文件有多大。
1、用VisualStudio6.0打开HelloWorld.cpp文件,直接按F7。然后点击OK,生成
Project文件,然后进行编译。编译完成了以后,看看Debug目录下的执行文件的大
小,为172,096Bytes。

2、刚才编译的Debug文件,现在修改成Release文件看看。选择Win32 Release,再
编译。察看执行文件大小,现在成了40,960Bytes。看来Debug版本的要比Release
的小。

3、检查代码优化:发现执行文件的优化是Maximize Speed。那么修改成Minimize
Size看看。重新编译,得到执行文件的大小为:40,960Bytes。看来大小没什么变
化。其实这是由于我们的代码本身太小的缘故,导致即使变化了也看不出来。

4、想想我们程序的main函数是由CRT类库进行引导的。在我们现在的设定当中,由
于采取的是系统缺省的编译连接方式(缺省为编译为Single Thread,Static
Library),所以,在我们的执行文件当中,包含了CRT的二进制代码。好,修改编
译选项:C/C++ => Category:Code Generation => Use run-time
library:MutiThreaded Dll。编译看看:执行文件大小变成了16,384Bytes。

5、刚才的设定确实不错,一下子把执行文件大小减小到了16K。现在用UltraEdit
看看执行文件都是些什么内容。结果大吃一惊:基本上都是0。看来这个有减小的
必要了。都知道,执行文件都有自己的代码段,数据段等等,每个段的大小也是采
用编译器缺省设定的。好,我们来修改一下段的大小看看:
5.1 连接选项中有一个是/opt:nowin98,意思是将段的大小设定成为Win2000适应
的。编译看看:哇塞,变成了2,560byte。看来这个选项确实把文件变小了N多。
5.2 在查察连接选项中还有没有什么特别的。发现/align:xx还可以将段大小缩
小。通过UltraEdit察看刚才/opt:nowin98编译出来的文件,发现每个段的大小都
是4K的整数倍。看来/align:xx还有减小的趋势。试一把再说:添加连接选项:
/align:16(这个大小已经是能够设定的最小的了)。看看结果:1,408Bytes。厉
害,现在代码更小了。
5.3 现在回想起来,执行文件大小有数据段,执行代码段等等,如果把这些段都合
并起来,是不是就会把段之间的冗余有减小了呢?再试试看:添加选项:
/merge:.data=.text /merge:.rdata=.text。再看看文件大小:1,328bytes。真的
很不错了。

6、刚才的设定确实不错,似乎达到了我们想要的极限了。但是回头想一下,如果
没有CRT库的话,会不会更小了?实际上确实这样。添加连接选项: /entry:
main,把入口地址直接指向我们的main函数看看。得到592Bytes。

最终我们得到我们最后的大小592Bytes了。我想这也许是我们通过编译器能够编译
出来的最小的代码了。

结论:
通过上述的步骤,我们了解了如何修改那些编译连接选项来达到执行文件瘦身的目
的。但是,通常来讲,在我们的Release文件当中,并不需要如此小的执行文件。
如果想达到瘦身的目的,修改为library:MutiThreaded Dll和添加/opt:nowin98已
经是很好的选择了。其他别的选项在编译的时候或多或少的有警告出现,而且,带
有那些编译选项编出来的执行文件也不一定在各个平台上能够适用。

另外:如果你的执行文件即使通过了这些设定还是比较大的话,也可以通过一些
EXE文件压缩工具来进行压缩。比如UPX等等。在此不再细说了。

VC环境下检查内存泄漏memory leak的方法

通过改写delete new方法,我们可以记录内存分配的地址,数量。因此,也就可以知道哪此内存在程序结束后没有释放。

将如下代码改存放为trace.cpp ,将trace.cpp放入要检测的工程。运行Debug调试程序,在Debug的输出里会有提示信息。

/**********************************************************************
Trace alloc
-----------
Purpose:

Implement a allocation check routine that reports the whole
callstack for each leaked allocation.

Based on the code for ExtendedTrace written by
Zoltan Csizmadia, zoltan_csizmadia@yahoo.com.

Author:

Erik Rydgren, erik@rydgrens.net.

Usage:
1/ Define DETECT_LEAKS in the project settings under
C++/preprocessor.

If you want checking of overwrites then define DETECT_OVERWRITES
in the project settings. Change the frequency of the checks by
altering the NML_CHECK_EVERY define in tracealloc.cpp.

2/ Compile.

If you get multiple defined symbols (overloaded new and delete)
add linker switch /FORCE:MULTIPLE on the exe and make sure the
tracealloc new and delete is the ones used. If not, reorder the
included libraries until they do.

**********************************************************************/

#if defined(_DEBUG) && defined(WIN32) //&& defined(DETECT_LEAKS)

#include
#include
#include
#include
#include
#include

using namespace std;

typedef std::basic_string > tcstring;

// Setup how much buffer is used for a single path fetch, increase if you get AV's during leak dump (4096 is plenty though)
#define BUFFERSIZE 4096

// Define how many levels of callstack that should be fetched for each allocation.
// Each level costs 2*sizof(ULONG) bytes / allocation.
#define MAXSTACK 5

// Define size of no mans land
#define NO_MANS_LAND_SIZE 16

// Define frequency of no mans land checking
#define NML_CHECK_EVERY 1000

#pragma comment( lib, "imagehlp.lib" )

void GetStackTrace(HANDLE hThread, ULONG ranOffsets[][2], ULONG nMaxStack );
void WriteStackTrace(ULONG ranOffsets[][2], ULONG nMaxStack, tcstring& roOut);
void* TraceAlloc(size_t nSize);
void TraceDealloc(void* poMem);

void OutputDebugStringFormat( LPCTSTR lpszFormat, ... )
{
TCHAR lpszBuffer[BUFFERSIZE];
va_list fmtList;

va_start( fmtList, lpszFormat );
_vstprintf( lpszBuffer, lpszFormat, fmtList );
va_end( fmtList );

::OutputDebugString( lpszBuffer );
}

// Unicode safe char* -> TCHAR* conversion
void PCSTR2LPTSTR( PCSTR lpszIn, LPTSTR lpszOut )
{
#if defined(UNICODE)||defined(_UNICODE)
ULONG index = 0;
PCSTR lpAct = lpszIn;

for( ; ; lpAct++ )
{
lpszOut[index++] = (TCHAR)(*lpAct);
if ( *lpAct == 0 )
break;
}
#else
// This is trivial :)
strcpy( lpszOut, lpszIn );
#endif
}

// Let's figure out the path for the symbol files
// Search path= ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;" + lpszIniPath
// Note: There is no size check for lpszSymbolPath!
void InitSymbolPath( PSTR lpszSymbolPath, PCSTR lpszIniPath )
{
CHAR lpszPath[BUFFERSIZE];

// Creating the default path
// ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;"
strcpy( lpszSymbolPath, "." );

// environment variable _NT_SYMBOL_PATH
if ( GetEnvironmentVariableA( "_NT_SYMBOL_PATH", lpszPath, BUFFERSIZE ) )
{
strcat( lpszSymbolPath, ";" );
strcat( lpszSymbolPath, lpszPath );
}

// environment variable _NT_ALTERNATE_SYMBOL_PATH
if ( GetEnvironmentVariableA( "_NT_ALTERNATE_SYMBOL_PATH", lpszPath, BUFFERSIZE ) )
{
strcat( lpszSymbolPath, ";" );
strcat( lpszSymbolPath, lpszPath );
}

// environment variable SYSTEMROOT
if ( GetEnvironmentVariableA( "SYSTEMROOT", lpszPath, BUFFERSIZE ) )
{
strcat( lpszSymbolPath, ";" );
strcat( lpszSymbolPath, lpszPath );
strcat( lpszSymbolPath, ";" );

// SYSTEMROOT\System32
strcat( lpszSymbolPath, lpszPath );
strcat( lpszSymbolPath, "\\System32" );
}

// Add user defined path
if ( lpszIniPath != NULL )
if ( lpszIniPath[0] != '\0' )
{
strcat( lpszSymbolPath, ";" );
strcat( lpszSymbolPath, lpszIniPath );
}
}

// Uninitialize the loaded symbol files
BOOL UninitSymInfo()
{
return SymCleanup( GetCurrentProcess() );
}

// Initializes the symbol files
BOOL InitSymInfo( PCSTR lpszInitialSymbolPath )
{
CHAR lpszSymbolPath[BUFFERSIZE];
DWORD symOptions = SymGetOptions();

symOptions |= SYMOPT_LOAD_LINES;
symOptions &= ~SYMOPT_UNDNAME;
SymSetOptions( symOptions );

// Get the search path for the symbol files
InitSymbolPath( lpszSymbolPath, lpszInitialSymbolPath );

return SymInitialize( GetCurrentProcess(), lpszSymbolPath, TRUE);
}

// Get the module name from a given address
BOOL GetModuleNameFromAddress( UINT address, LPTSTR lpszModule )
{
BOOL ret = FALSE;
IMAGEHLP_MODULE moduleInfo;

::ZeroMemory( &moduleInfo, sizeof(moduleInfo) );
moduleInfo.SizeOfStruct = sizeof(moduleInfo);

if ( SymGetModuleInfo( GetCurrentProcess(), (DWORD)address, &moduleInfo ) )
{
// Got it!
PCSTR2LPTSTR( moduleInfo.ModuleName, lpszModule );
ret = TRUE;
}
else
// Not found :(
_tcscpy( lpszModule, _T("?") );

return ret;
}

// Get function prototype and parameter info from ip address and stack address
BOOL GetFunctionInfoFromAddresses( ULONG fnAddress, ULONG stackAddress, LPTSTR lpszSymbol )
{
BOOL ret = FALSE;
DWORD dwDisp = 0;
DWORD dwSymSize = 10000;
TCHAR lpszUnDSymbol[BUFFERSIZE]=_T("?");
CHAR lpszNonUnicodeUnDSymbol[BUFFERSIZE]="?";
LPTSTR lpszParamSep = NULL;
LPCTSTR lpszParsed = lpszUnDSymbol;
PIMAGEHLP_SYMBOL pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc( GMEM_FIXED, dwSymSize );

::ZeroMemory( pSym, dwSymSize );
pSym->SizeOfStruct = dwSymSize;
pSym->MaxNameLength = dwSymSize - sizeof(IMAGEHLP_SYMBOL);

// Set the default to unknown
_tcscpy( lpszSymbol, _T("?") );

// Get symbol info for IP
if ( SymGetSymFromAddr( GetCurrentProcess(), (ULONG)fnAddress, &dwDisp, pSym ) )
{
// Make the symbol readable for humans
UnDecorateSymbolName( pSym->Name, lpszNonUnicodeUnDSymbol, BUFFERSIZE,
UNDNAME_COMPLETE |
UNDNAME_NO_THISTYPE |
UNDNAME_NO_SPECIAL_SYMS |
UNDNAME_NO_MEMBER_TYPE |
UNDNAME_NO_MS_KEYWORDS |
UNDNAME_NO_ACCESS_SPECIFIERS );

// Symbol information is ANSI string
PCSTR2LPTSTR( lpszNonUnicodeUnDSymbol, lpszUnDSymbol );

// I am just smarter than the symbol file :)
if ( _tcscmp(lpszUnDSymbol, _T("_WinMain@16")) == 0 )
_tcscpy(lpszUnDSymbol, _T("WinMain(HINSTANCE,HINSTANCE,LPCTSTR,int)"));
else
if ( _tcscmp(lpszUnDSymbol, _T("_main")) == 0 )
_tcscpy(lpszUnDSymbol, _T("main(int,TCHAR * *)"));
else
if ( _tcscmp(lpszUnDSymbol, _T("_mainCRTStartup")) == 0 )
_tcscpy(lpszUnDSymbol, _T("mainCRTStartup()"));
else
if ( _tcscmp(lpszUnDSymbol, _T("_wmain")) == 0 )
_tcscpy(lpszUnDSymbol, _T("wmain(int,TCHAR * *,TCHAR * *)"));
else
if ( _tcscmp(lpszUnDSymbol, _T("_wmainCRTStartup")) == 0 )
_tcscpy(lpszUnDSymbol, _T("wmainCRTStartup()"));

lpszSymbol[0] = _T('\0');

// Let's go through the stack, and modify the function prototype, and insert the actual
// parameter values from the stack
if ( _tcsstr( lpszUnDSymbol, _T("(void)") ) == NULL && _tcsstr( lpszUnDSymbol, _T("()") ) == NULL)
{
ULONG index = 0;
for( ; ; index++ )
{
lpszParamSep = _tcschr( lpszParsed, _T(',') );
if ( lpszParamSep == NULL )
break;

*lpszParamSep = _T('\0');

_tcscat( lpszSymbol, lpszParsed );
_stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X,"), *((ULONG*)(stackAddress) + 2 + index) );

lpszParsed = lpszParamSep + 1;
}

lpszParamSep = _tcschr( lpszParsed, _T(')') );
if ( lpszParamSep != NULL )
{
*lpszParamSep = _T('\0');

_tcscat( lpszSymbol, lpszParsed );
_stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X)"), *((ULONG*)(stackAddress) + 2 + index) );

lpszParsed = lpszParamSep + 1;
}
}

_tcscat( lpszSymbol, lpszParsed );

ret = TRUE;
}

GlobalFree( pSym );

return ret;
}

// Get source file name and line number from IP address
// The output format is: "sourcefile(linenumber)" or
// "modulename!address" or
// "address"
BOOL GetSourceInfoFromAddress( UINT address, LPTSTR lpszSourceInfo )
{
BOOL ret = FALSE;
IMAGEHLP_LINE lineInfo;
DWORD dwDisp;
TCHAR lpszFileName[BUFFERSIZE] = _T("");
TCHAR lpModuleInfo[BUFFERSIZE] = _T("");

_tcscpy( lpszSourceInfo, _T("?(?)") );

::ZeroMemory( &lineInfo, sizeof( lineInfo ) );
lineInfo.SizeOfStruct = sizeof( lineInfo );

if ( SymGetLineFromAddr( GetCurrentProcess(), address, &dwDisp, &lineInfo ) )
{
// Got it. Let's use "sourcefile(linenumber)" format
PCSTR2LPTSTR( lineInfo.FileName, lpszFileName );
_stprintf( lpszSourceInfo, _T("%s(%d)"), lpszFileName, lineInfo.LineNumber );
ret = TRUE;
}
else
{
// There is no source file information. :(
// Let's use the "modulename!address" format
GetModuleNameFromAddress( address, lpModuleInfo );

if ( lpModuleInfo[0] == _T('?') || lpModuleInfo[0] == _T('\0'))
// There is no modulename information. :((
// Let's use the "address" format
_stprintf( lpszSourceInfo, _T("0x%08X"), lpModuleInfo, address );
else
_stprintf( lpszSourceInfo, _T("%s!0x%08X"), lpModuleInfo, address );

ret = FALSE;
}

return ret;
}

void GetStackTrace(HANDLE hThread, ULONG ranOffsets[][2], ULONG nMaxStack )
{
STACKFRAME callStack;
BOOL bResult;
CONTEXT context;
TCHAR symInfo[BUFFERSIZE] = _T("?");
TCHAR srcInfo[BUFFERSIZE] = _T("?");
HANDLE hProcess = GetCurrentProcess();

// If it's not this thread, let's suspend it, and resume it at the end
if ( hThread != GetCurrentThread() )
if ( SuspendThread( hThread ) == -1 )
{
// whaaat ?!
OutputDebugStringFormat( _T("Call stack info(thread=0x%X) failed.\n") );
return;
}

::ZeroMemory( &context, sizeof(context) );
context.ContextFlags = CONTEXT_FULL;

if ( !GetThreadContext( hThread, &context ) )
{
OutputDebugStringFormat( _T("Call stack info(thread=0x%X) failed.\n") );
return;
}

::ZeroMemory( &callStack, sizeof(callStack) );
callStack.AddrPC.Offset = context.Eip;
callStack.AddrStack.Offset = context.Esp;
callStack.AddrFrame.Offset = context.Ebp;
callStack.AddrPC.Mode = AddrModeFlat;
callStack.AddrStack.Mode = AddrModeFlat;
callStack.AddrFrame.Mode = AddrModeFlat;

for( ULONG index = 0; ; index++ )
{
bResult = StackWalk(
IMAGE_FILE_MACHINE_I386,
hProcess,
hThread,
&callStack,
NULL,
NULL,
SymFunctionTableAccess,
SymGetModuleBase,
NULL);

// Ignore the first two levels (it's only TraceAlloc and operator new anyhow)
if ( index < 3 )
continue;

// Break if we have fetched nMaxStack levels
if ( index-3 == nMaxStack)
break;

// If we are at the top of the stackframe then break.
if( !bResult || callStack.AddrFrame.Offset == 0) {
ranOffsets[index-3][0] = 0;
ranOffsets[index-3][1] = 0;
break;
}

// Remember program counter and frame pointer
ranOffsets[index-3][0] = callStack.AddrPC.Offset;
ranOffsets[index-3][1] = callStack.AddrFrame.Offset;
}

if ( hThread != GetCurrentThread() )
ResumeThread( hThread );
}

void WriteStackTrace(ULONG ranOffsets[][2], ULONG nMaxStack, tcstring& roOut)
{
TCHAR symInfo[BUFFERSIZE] = _T("?");
TCHAR srcInfo[BUFFERSIZE] = _T("?");

for (ULONG index = 0; index < nMaxStack && ranOffsets[index][0] != 0 && ranOffsets[index][1] != 0; index++) {
GetFunctionInfoFromAddresses( ranOffsets[index][0], ranOffsets[index][1], symInfo );
GetSourceInfoFromAddress( ranOffsets[index][0], srcInfo );

roOut += _T(" ");
roOut += srcInfo;
roOut += _T(" : ");
roOut += symInfo;
roOut += _T("\n");
}
}

struct sdAllocBlock {
unsigned long nMagicNumber;
sdAllocBlock* poNext;
sdAllocBlock* poPrev;
size_t nSize;
ULONG anStack[MAXSTACK][2];
char pzNoMansLand[NO_MANS_LAND_SIZE];

sdAllocBlock()
{
Init();
}

void Init() {
poNext = this;
poPrev = this;
nMagicNumber = 0x55555555;
}

void Disconnect() {
if (poNext != this) {
poNext->poPrev = poPrev;
poPrev->poNext = poNext;
poNext = this;
poPrev = this;
}
}

void ConnectTo(sdAllocBlock* poPos) {
Disconnect();
poPrev = poPos;
poNext = poPos->poNext;
poPos->poNext->poPrev = this;
poPos->poNext = this;
}
};

void LeakDump(tcstring& roOut);

class CS {
CRITICAL_SECTION cs;
public:
CS() { InitializeCriticalSection(&cs); }
~CS() { }
operator CRITICAL_SECTION& () { return cs; }
};

class Guard {
CRITICAL_SECTION& rcs;
public:
Guard(CRITICAL_SECTION& rcs)
: rcs(rcs) { EnterCriticalSection(&rcs); }
~Guard() { LeaveCriticalSection(&rcs); }
};


class cLeakDetector
{
public:

cLeakDetector() {
InitSymInfo(NULL);
}

~cLeakDetector() {
tcstring leaks;
LeakDump(leaks);
OutputDebugString(leaks.c_str());
UninitSymInfo();
}
};

static unsigned int nNumAllocs = 0;
static unsigned int nCurrentAllocs = 0;
static unsigned int nMaxConcurrent = 0;

CS& Gate() {
static CS cs;
return cs;
}

sdAllocBlock& Head()
{
static cLeakDetector oDetector;
static sdAllocBlock oHead;
return oHead;
}

class cInitializer {
public: cInitializer() { Head(); };
} oInitalizer;

void LeakDump(tcstring& roOut)
{
Guard at(Gate());

TCHAR buffer[65];

sdAllocBlock* poBlock = Head().poNext;
while (poBlock != &Head()) {
tcstring stack;
WriteStackTrace(poBlock->anStack, MAXSTACK, stack);

bool bIsKnownLeak = false;

// afxMap leaks is MFC. Not ours.
if (stack.find(_T(": afxMap")) != tcstring::npos)
bIsKnownLeak = true;

if (!bIsKnownLeak) {
roOut += _T("Leak of ");
roOut += _itot(poBlock->nSize, buffer, 10);
roOut += _T(" bytes detected:\n");
roOut += stack;
roOut += _T("\n");
}

poBlock = poBlock->poNext;
}

roOut += _T("Memory statistics\n-----------------\n");
roOut += _T("Total allocations: ");
roOut += _itot(nNumAllocs, buffer, 10);
roOut += _T("\n");
roOut += _T("Max concurrent allocations: ");
roOut += _itot(nMaxConcurrent, buffer, 10);
roOut += _T("\n");
}


bool AssertMem(char* m, char c, size_t s)
{
for (size_t i = 0; i < s; i++)
if (m[i] != c) break;
return i >= s;
}

void CheckNoMansLand()
{
Guard at(Gate());

sdAllocBlock* poBlock = Head().poNext;
while (poBlock != &Head()) {
if (!AssertMem(poBlock->pzNoMansLand, 0x55, NO_MANS_LAND_SIZE)) {
bool MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD = false;
tcstring stack;
WriteStackTrace(poBlock->anStack, MAXSTACK, stack);
assert(MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD);
}
char* pzNoMansLand = ((char*)poBlock) + sizeof(sdAllocBlock) + poBlock->nSize;
if (!AssertMem(pzNoMansLand, 0x55, NO_MANS_LAND_SIZE)) {
bool MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_TAIL = false;
tcstring stack;
WriteStackTrace(poBlock->anStack, MAXSTACK, stack);
assert(MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_TAIL);
}
poBlock = poBlock->poNext;
}
}

void* TraceAlloc(size_t nSize)
{
Guard at(Gate());

nNumAllocs++;
#ifdef DETECT_OVERWRITES
if (nNumAllocs % NML_CHECK_EVERY == 0) {
CheckNoMansLand();
}
#endif

sdAllocBlock* poBlock = (sdAllocBlock*) malloc(nSize + sizeof(sdAllocBlock) + NO_MANS_LAND_SIZE);
poBlock->Init();
poBlock->nSize = nSize;
char* pzNoMansLand = ((char*)poBlock) + sizeof(sdAllocBlock) + poBlock->nSize;
memset(poBlock->pzNoMansLand, 0x55, NO_MANS_LAND_SIZE);
memset(pzNoMansLand, 0x55, NO_MANS_LAND_SIZE);

GetStackTrace(GetCurrentThread(), poBlock->anStack, MAXSTACK );

poBlock->ConnectTo(&Head());
nCurrentAllocs++;
if (nCurrentAllocs > nMaxConcurrent)
nMaxConcurrent = nCurrentAllocs;
return (void*)(((char*) poBlock) + sizeof(sdAllocBlock));
}


void TraceDealloc(void* poMem)
{
Guard at(Gate());

if (!poMem) return; // delete NULL; = do nothing

sdAllocBlock* poBlock = (sdAllocBlock*) ((char*)poMem - sizeof(sdAllocBlock));
char* pzNoMansLand = ((char*)poBlock) + sizeof(sdAllocBlock) + poBlock->nSize;

if (poBlock->nMagicNumber != 0x55555555) {
// Whupps, something fishy is going on

// Validate the address against our list of allocated blocks
sdAllocBlock* poLoopBlock = Head().poNext;
while (poLoopBlock != &Head() && poLoopBlock != poBlock)
poLoopBlock = poLoopBlock->poNext;
if (poLoopBlock == &Head()) {
// Hell we didn't allocate this block.
// Just free the memory and hope for the best.
free(poMem);
}
else {
bool MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD = false;
assert(MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD);
}
}
else if (!AssertMem(poBlock->pzNoMansLand, 0x55, NO_MANS_LAND_SIZE)) {
bool MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD = false;
assert(MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_LEAD);
}
else if (!AssertMem(pzNoMansLand, 0x55, NO_MANS_LAND_SIZE)) {
bool MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_TAIL = false;
assert(MEMORYERROR_STUFF_WRITTEN_IN_NOMANSLAND_TAIL);
}
else {
poBlock->Disconnect();
free(poBlock);
nCurrentAllocs--;
}
}

// Take over global new and delete
void* operator new(size_t s)
{
return TraceAlloc(s);
}

void* operator new[](size_t s)
{
return TraceAlloc(s);
}

void operator delete(void* pMem)
{
TraceDealloc(pMem);
}

void operator delete[] (void* pMem)
{
TraceDealloc(pMem);
}

// And then some crap for taking over MFC allocations.
void* __cdecl operator new(size_t s, LPCSTR lpszFileName, int nLine)
{
return TraceAlloc(s);
}

void* __cdecl operator new[](size_t s, LPCSTR lpszFileName, int nLine)
{
return TraceAlloc(s);
}

void __cdecl operator delete(void* pMem, LPCSTR /* lpszFileName */, int /* nLine */)
{
TraceDealloc(pMem);
}

void __cdecl operator delete[](void* pMem, LPCSTR /* lpszFileName */, int /* nLine */)
{
TraceDealloc(pMem);
}

#endif