2012年12月8日 星期六

[AOSP] Build Android Framework

Just brief note the steps to build AOSP

PC: i5-3210, 8G RAM, 750G HD
OS: Ubuntu 10.04 64 bits on VM WorkStation 8.0
Code Name: Jelly Bean
Tag: android-4.1.2_r1

Set up environment  ===========
1. Install Ubuntu 10.04 64 bits.
       http://releases.ubuntu.com/lucid/

2. Install Python.
$ sudo apt-get install python.
 
3. Install make
$ sudo apt-get update
$ sudo apt-get install gcc g++ build-essential
 
4. Install JDK6
$ sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

 * If you got message below in step 4:
   Package sun-java6-jdk is not available, but is referred to by another package.
   This may mean that the package is missing, has been obsoleted, or
   is only available from another source
   E: Package 'sun-java6-jdk' has no installation candidate

 * Use following command instead
$ sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

5. Install git
$ sudo apt-get install git-core

6. Install Required Package
$ sudo apt-get install git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc

7. Configuring USB Access
$ sudo gedit /etc/udev/rules.d/51-android.rules

 * Paste following text into the editing file and replace <username> to actual username

# adb protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e12", MODE="0600", OWNER="<username>"
# fastboot protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", ATTR{idProduct}=="0fff", MODE="0600", OWNER="<username>"
# adb protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e22", MODE="0600", OWNER="<username>"
# fastboot protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e20", MODE="0600", OWNER="<username>"
# adb protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", ATTR{idProduct}=="70a9", MODE="0600", OWNER="<username>"
# fastboot protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="708c", MODE="0600", OWNER="<username>"
# adb protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", ATTR{idProduct}=="6860", MODE="0600", OWNER="<username>"
# fastboot protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e30", MODE="0600", OWNER="<username>"
# adb protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d101", MODE="0600", OWNER="<username>"
# fastboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d022", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d00f", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard ES)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d010", MODE="0600", OWNER="<username>"
# adb protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e42", MODE="0600", OWNER="<username>"
# fastboot protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e40", MODE="0600", OWNER="<username>"


  * After you save the file, execute following command.
    $ sudo chmod a+r /etc/udev/rules.d/51-android.rules

8. Setting up ccache
$ export USE_CCACHE=1


Download source  ============
1. Create a bin/ directory in home directory and make it included in path.
$ mkdir ~/bin
$ PATH=~/bin:$PATH

2. Download the Repo script
$ curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$ chmod a+x ~/bin/repo

3. Create a working directory, the name is up to you.
$ mkdir WORKING_DIRECTORY
$ cd WORKING_DIRECTORY

4. Run repo init
$ repo init -u https://android.googlesource.com/platform/manifest

5. Check out branch
$ repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.2_r1

6. Start to download
$ repo sync

7. Verifying Git Tags, I don't know what the step for.
$ gpg --import

  * Paste following text, then enter Ctrl-D

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

mQGiBEnnWD4RBACt9/h4v9xnnGDou13y3dvOx6/t43LPPIxeJ8eX9WB+8LLuROSV
lFhpHawsVAcFlmi7f7jdSRF+OvtZL9ShPKdLfwBJMNkU66/TZmPewS4m782ndtw7
8tR1cXb197Ob8kOfQB3A9yk2XZ4ei4ZC3i6wVdqHLRxABdncwu5hOF9KXwCgkxMD
u4PVgChaAJzTYJ1EG+UYBIUEAJmfearb0qRAN7dEoff0FeXsEaUA6U90sEoVks0Z
wNj96SA8BL+a1OoEUUfpMhiHyLuQSftxisJxTh+2QclzDviDyaTrkANjdYY7p2cq
/HMdOY7LJlHaqtXmZxXjjtw5Uc2QG8UY8aziU3IE9nTjSwCXeJnuyvoizl9/I1S5
jU5SA/9WwIps4SC84ielIXiGWEqq6i6/sk4I9q1YemZF2XVVKnmI1F4iCMtNKsR4
MGSa1gA8s4iQbsKNWPgp7M3a51JCVCu6l/8zTpA+uUGapw4tWCp4o0dpIvDPBEa9
b/aF/ygcR8mh5hgUfpF9IpXdknOsbKCvM9lSSfRciETykZc4wrRCVGhlIEFuZHJv
aWQgT3BlbiBTb3VyY2UgUHJvamVjdCA8aW5pdGlhbC1jb250cmlidXRpb25AYW5k
cm9pZC5jb20+iGAEExECACAFAknnWD4CGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIX
gAAKCRDorT+BmrEOeNr+AJ42Xy6tEW7r3KzrJxnRX8mij9z8tgCdFfQYiHpYngkI
2t09Ed+9Bm4gmEO5Ag0ESedYRBAIAKVW1JcMBWvV/0Bo9WiByJ9WJ5swMN36/vAl
QN4mWRhfzDOk/Rosdb0csAO/l8Kz0gKQPOfObtyYjvI8JMC3rmi+LIvSUT9806Up
hisyEmmHv6U8gUb/xHLIanXGxwhYzjgeuAXVCsv+EvoPIHbY4L/KvP5x+oCJIDbk
C2b1TvVk9PryzmE4BPIQL/NtgR1oLWm/uWR9zRUFtBnE411aMAN3qnAHBBMZzKMX
LWBGWE0znfRrnczI5p49i2YZJAjyX1P2WzmScK49CV82dzLo71MnrF6fj+Udtb5+
OgTg7Cow+8PRaTkJEW5Y2JIZpnRUq0CYxAmHYX79EMKHDSThf/8AAwUIAJPWsB/M
pK+KMs/s3r6nJrnYLTfdZhtmQXimpoDMJg1zxmL8UfNUKiQZ6esoAWtDgpqt7Y7s
KZ8laHRARonte394hidZzM5nb6hQvpPjt2OlPRsyqVxw4c/KsjADtAuKW9/d8phb
N8bTyOJo856qg4oOEzKG9eeF7oaZTYBy33BTL0408sEBxiMior6b8LrZrAhkqDjA
vUXRwm/fFKgpsOysxC6xi553CxBUCH2omNV6Ka1LNMwzSp9ILz8jEGqmUtkBszwo
G1S8fXgE0Lq3cdDM/GJ4QXP/p6LiwNF99faDMTV3+2SAOGvytOX6KjKVzKOSsfJQ
hN0DlsIw8hqJc0WISQQYEQIACQUCSedYRAIbDAAKCRDorT+BmrEOeCUOAJ9qmR0l
EXzeoxcdoafxqf6gZlJZlACgkWF7wi2YLW3Oa+jv2QSTlrx4KLM=
=Wi5D
-----END PGP PUBLIC KEY BLOCK-----


Build   ===================
1. Set up environment
        $ . build/envsetup.sh

2. Choose a Target
        $ lunch full-eng

3. Build
        $ make -j4

The building process is done if you see message below.
Install system fs image: out/target/product/generic/system.img


Run on emulator  ===========
1. Boot up emulator.
        $ emulator


Reference:
http://source.android.com/source/index.html

[AOSP] make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java]

Problem:
When I built Android Framandroid-4.1.2_r1 on Ubuntu, I got the error message below.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Vector.<init>(Vector.java:111)
at java.util.Vector.<init>(Vector.java:124)
at org.antlr.analysis.DFA.createTransitionTableEntryForState(DFA.java:551)
at org.antlr.analysis.DFA.createStateTables(DFA.java:440)
at org.antlr.codegen.CodeGenerator.genLookaheadDecision(CodeGenerator.java:645)
at org.antlr.grammar.v3.CodeGenTreeWalker.block(CodeGenTreeWalker.java:2876)
at org.antlr.grammar.v3.CodeGenTreeWalker.rule(CodeGenTreeWalker.java:2382)
at org.antlr.grammar.v3.CodeGenTreeWalker.rules(CodeGenTreeWalker.java:1537)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammarSpec(CodeGenTreeWalker.java:1441)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammar_(CodeGenTreeWalker.java:461)
at org.antlr.codegen.CodeGenerator.genRecognizer(CodeGenerator.java:421)
at org.antlr.Tool.generateRecognizer(Tool.java:655)
at org.antlr.Tool.process(Tool.java:468)
at org.antlr.Tool.main(Tool.java:93)
make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java] Error 1
make: *** Waiting for unfinished jobs....



Solution:
Open file in  
external/smali/smali/Android.mk
Find the line 
$(GEN): PRIVATE_CUSTOM_TOOL = java -jar $(ANTLR_JAR) -fo $(dir $@) $<
Change it to 
$(GEN): PRIVATE_CUSTOM_TOOL = java -Xmx512m -jar $(ANTLR_JAR) -fo $(dir $@) $<


Reference:
https://groups.google.com/forum/#!msg/android-building/Or1C6bpq8GQ/xAEMEEM0gKAJ


**********************************************************************
Related issues:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.lang.String.toCharArray(String.java:2726)
at java.util.zip.ZipOutputStream.getUTF8Bytes(ZipOutputStream.java:483)
at java.util.zip.ZipOutputStream.writeLOC(ZipOutputStream.java:348)
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:179)
at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:92)
at com.android.tools.layoutlib.create.AsmGenerator.createJar(AsmGenerator.java:241)
at com.android.tools.layoutlib.create.AsmGenerator.generate(AsmGenerator.java:225)
at com.android.tools.layoutlib.create.Main.main(Main.java:98)
make: *** [out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar] Error 1
make: *** Deleting file `out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar'

Edit the file
frameworks/base/tools/layoutlib/Android.mk

Reference:
https://groups.google.com/forum/?fromgroups=#!topic/android-building/D3QmmvsMRME


2012年12月7日 星期五

error LNK2005: * already defined in *.lib(*.obj)

Problem:
When I build Seahorse in branch bsquare, sometimes I got lots of linking error like this
error LNK2005: * already defined in *.obj
I’m sure it had been successful built before, but it doesn’t work now.


Solution:
I found it can be avoid if putting /FORCE:MULTIPLE into build options.
Right click on project -> Properties -> Linker -> Command Line -> Additional Options -> add /FORCE:MULTIPLE

(It just a first-add, please see the first reference for root cause.)


Reference:
http://stackoverflow.com/questions/10046485/error-lnk2005-already-defined
http://bbs.csdn.net/topics/260087335

2012年11月27日 星期二

[Webkit] KeywordLookupGenerator.py throws error of "expected description ending with @end"

Problem:
Python throw an exception from file KeywordLookupGenerator.py.
According to building log, it run into error at line 79.
I found that is a ending issue.

Solution:

In line 79 of my KeywordLookupGenerator.py:
    if not terminator == "@end"

Change it to:
    if not terminator.rstrip() == "@end"



Reference:
https://lists.webkit.org/pipermail/webkit-unassigned/2011-June/340772.html

2012年11月8日 星期四

[CMake] Error: The source "Path1/CMakeLists.txt" does not match the source "Path2/CMakeLists.txt" us ed to generate cache.

Error:

CMake Error: The source "Path1/CMakeLists.txt" does not match the source "Path2/CMakeLists.txt" used to generate cache.  Re-run cmake with a different source directory.

Solution:
Delete CMakeCache.txt in the target folder.



2012年11月7日 星期三

error C2731: 'WinMain' : function cannot be overloaded

Error message as title.

My code as below.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)

{
    bala...bala...
}

To fix the issue, change code to
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    bala...bala...
}

2012年11月3日 星期六

fatal error LNK1181: cannot open input file 'mmtimer.lib'

Error:
fatal error LNK1181: cannot open input file 'mmtimer.lib

Solution:
mmtimer.lib is for OS WinCE
For Windows, It should be winmm.lib

1. go to Project properties->Linker->input
2. remove mmtimer.lib and put winmm.lib instead.

Reference:
http://www.programmer-club.com/showSameTitleN/directx/5570.html

error C3861: '_ASSERTE': identifier not found


Error:
error C3861: '_ASSERTE': identifier not found

Solution:
The reason for this is, there is a crtdbg.h in project. so #include crtdbg.h goes to own crtdbg.h

1. In my case, tt is caused _ASSERTE doesn't defined in wceshunt.
    Please remove path wceshunt\include from include directories.

2. If the path already be removed, such as project icu.
    Please add C:\Program Files\Microsoft Visual Studio 9.0\VC\include to include directories. It should be added ahead wceshunt\include if you don't remove wceshunt from include directories.



2012年10月31日 星期三

[bash] $'\r': command not found


Error:
I got message below when I execute a bash script.
D:/asmbin/gnuasm: line 2: $'\r': command not found
D:/asmbin/gnuasm: line 4: $'\r': command not found

Solution:
It is caused by end of line is Windows style '\n\r'
Unix think the eol should be '\n'
Mac think the eol should be '\r'

The bash is unix environment, so we have to change '\n\r' to 'n'.
I use notepad++ as editor to fix the script.

Reference:
http://stackoverflow.com/questions/11616835/cgywin-r-command-not-found-bashrc-bash-profile
http://chunshucaca.blog.163.com/blog/static/6045100020082317363713/

[bash] MS-DOS style path detected


Error:
I got message below when I execute a bash script.
cygwin warning:
  MS-DOS style path detected: D:/asmbin/gnuasm
  Preferred POSIX equivalent is: /cygdrive/d/asmbin/gnuasm
  CYGWIN environment variable option "nodosfilewarning" turns off this warning.
  Consult the user's guide for more details about POSIX paths:
    http://cygwin.com/cygwin-ug-net/using.html#using-pathnames

Solution:
To ignore the message, please add "set CYGWIN=nodosfilewarning" in head of script

Reference:
http://blog.csdn.net/liuhongjavaen/article/details/7254077

2012年10月30日 星期二

[.Net] Dumpbin to see the contents of windows library (*.lib)


To view what functions inside lib file, we can open "Visual Studio Command Prompt", and type "Dumpbin /exports [file_path]" to show all functions be implemented.

C:\Program Files\Microsoft Visual Studio 9.0\VC>dumpbin /exports "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib\libegl.lib"
Microsoft (R) COFF/PE Dumper Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib\libegl.lib

File Type: LIBRARY

     Exports

       ordinal    name

            14    eglBindAPI
            20    eglBindTexImage
             7    eglChooseConfig
            33    eglCopyBuffers
            23    eglCreateContext
            18    eglCreatePbufferFromClientBuffer
            10    eglCreatePbufferSurface
            11    eglCreatePixmapSurface
             9    eglCreateWindowSurface
            24    eglDestroyContext
            12    eglDestroySurface
             8    eglGetConfigAttrib
             6    eglGetConfigs
            26    eglGetCurrentContext
            28    eglGetCurrentDisplay
            27    eglGetCurrentSurface
             2    eglGetDisplay
             1    eglGetError
            34    eglGetProcAddress
             3    eglInitialize
            25    eglMakeCurrent
            15    eglQueryAPI
            29    eglQueryContext
             5    eglQueryString
            13    eglQuerySurface
            21    eglReleaseTexImage
            17    eglReleaseThread
            19    eglSurfaceAttrib
            32    eglSwapBuffers
            22    eglSwapInterval
             4    eglTerminate
            16    eglWaitClient
            30    eglWaitGL
            31    eglWaitNative

  Summary

          C3 .debug$S
          14 .idata$2
          14 .idata$3
           4 .idata$4
           4 .idata$5
           C .idata$6


You also can type "Dumpbin /exports /out:[outFile] [file_path]" to list all functions in text file if functions are too many to show in screen.

Reference:

2012年10月22日 星期一

[CMake] Some settings for VS project file

This is a simple note that showing some statement in CMakeList.txt to configure setting of VS project.

To add Preprocessor Definitions.
add_definitions(-DNOENTRY)










To add Additional Include Directories.

INCLUDE_DIRECTORIES(${VCInstallDir}/include/sys)










To modify Runtime Library.
STRING(REPLACE "/MTd" "/MDd" CMAKE_CXX_FLAGS_DEBUG
${CMAKE_CXX_FLAGS_DEBUG})
STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_RELWITHDEBINFO ${CMAKE_CXX_FLAGS_RELWITHDEBINFO})
STRING(REPLACE "/MT" "/MD" CMAKE_CXX_FLAGS_MINSIZEREL ${CMAKE_CXX_FLAGS_MINSIZEREL})








To Exclude Build Project from solution.
If project is added by this line add_library(foo EXCLUDE_FROM_ALL foo.c)
Add statement below to exclude project from build.
set_target_properties(foo PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD 1)



[Git] error: bad index file sha1 signature fatal: index file corrupt

Error:
I got an error message below.
$ git pull --rebase
error: bad index file sha1 signature
fatal: index file corrupt
error: bad index file sha1 signature
fatal: index file corrupt
error: bad index file sha1 signature
fatal: index file corrupt
Cannot pull with rebase: You have unstaged changes.
error: bad index file sha1 signature
fatal: index file corrupt
Additionally, your index contains uncommitted changes.
Please commit or stash them.


Solve:
1. Delete file .git/index
2. git reset --hard HEAD


Reference:
http://blog.wu-boy.com/2010/08/git-%E7%89%88%E6%9C%AC%E6%8E%A7%E5%88%B6%EF%BC%9A%E5%88%A9%E7%94%A8-git-reset-%E6%81%A2%E5%BE%A9%E6%AA%94%E6%A1%88%E3%80%81%E6%9A%AB%E5%AD%98%E7%8B%80%E6%85%8B%E3%80%81commit-%E8%A8%8A%E6%81%AF/

2012年10月11日 星期四

[Webkit] fatal error LNK1106: invalid file or disk full

Problem:
Build Webkit on VS2008+Windows 7 32-bit, got the error message as title.
fatal error LNK1106: invalid file or disk full

Solve:
Install the VS2005 hot fix KB949009
https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=18623

It is very weird for VS2008, perhaps I had installed VS 2005 before.

Reference:
http://lists.macosforge.org/pipermail/webkit-help/2010-May/001141.html

2012年10月8日 星期一

[Webkit] error LNK2019: unresolved external symbol localtime_s referenced in function localtimeOffset

When I build webkit with WinCE 6.0 SDK, I got the error message as title.
error LNK2019: unresolved external symbol localtime_s referenced in function localtimeOffset

To solve the problem, I remove the code in bold font below.

#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
//#define HAVE_LOCALTIME_S 1
#endif


After that, I got the error message below.
error C2040: 'localtime' : 'tm *(const time_t *)' differs in levels of indirection from 'int ()'

To solve the problem, I add the code before where function localtime is called.
struct tm *__cdecl localtime(const time_t *t);



Reference:
http://web.archiveorange.com/archive/v/fwvdeo1G1weLoWDuyUPP
http://hi.baidu.com/lihex/item/2243dfe144e14ef82a09a4d4
http://stackoverflow.com/questions/6380981/c-c-c4047-differs-in-levels-of-indirection-from-int

[Webkit] Memory Leak in GraphicContext

* BSQUARE Corp. and I remain the copyright of the code and article.

[Memory Leak in GraphicContext]
The function in GraphicContextCairoWin.cpp below will allocate a memory block to cairo_t*
static cairo_t* createCairoContextWithHDC(HDC hdc, bool hasAlpha)

We have to release memory when platform destory in GraphicContextCairo.cpp

void GraphicsContext::platformDestroy()
{
RefPtr<cairo_t> cr = platformContext()->cr();
cr.~RefPtr();
    delete m_data;
}




2012年10月1日 星期一

[CMake] Re-run cmake with a different source directory.

Problem:
CMake Error: The source "Path1/CMakeLists.txt" does not match the source "Path2/CMakeLists.txt" used to generate cache.  Re-run cmake with a different source
directory.


I got above error message when I execute below cmake command to generate solution for webkit.
cmake -G "Visual Studio 9 2008" -DCMAKE_WINCE_SDK="SDK_Name" -DPORT=WinCE -D3RDPARTY_DIR=Path1 Path2


Solve:
Delete CMakeCache.txt in the folder you executing cmake.









[Webkit] Failed to determine path to Apple Application Support directory

Problem:
After I successful build webkit by VS 2008 in Windows 7. I try to start up MiniBrowser.exe or WinLauncher.exe, and I got the error message as title.
Failed to determine path to Apple Application Support directory










Solve:
Edit registry table 
Add key Apple Application Support into HKEY_LOCAL_MACHINE\SOFTWARE\Apple Inc.
Then add string value 'InstallDir', 'UserVisibleVersion' and 'Version' as figure below.













Reference:
http://www.cnblogs.com/xyz2abc/archive/2012/04/09/2438913.html

[Webkit] Can't locate http/date.pm in @inc

Problem:
I got an error message as title when I try to update webkit auxiliary library.











Solve:
It is caused by our Cygwin’s Perl package is missing the HTTP/Date.pm module.
Type cpan HTTP::Date to fix.











Update again.








Reference:
http://blog.ashodnakashian.com/2012/09/






2012年9月28日 星期五

error LNK2019: unresolved external symbol WinMain referenced in function WinMainCRTStartupHelper

Problem: 
I add an console project to my main project, and I got the error message as title in linking phase.
error LNK2019: unresolved external symbol WinMain referenced in function WinMainCRTStartupHelper

Solve:
Right click on project -> Properties -> Linker -> Entry Point -> type 'wmain'
It is because my project entry point is _tmain and it will link to _tWinMain for CE OS.
So, we have to specify our entry point.


Reference:
Source code in tchar.h
#define _tmain          wmain

#ifdef UNDER_CE
#   define _tWinMain    WinMain // On CE it's always WinMain
#else
#   define _tWinMain    wWinMain
#endif

2012年9月27日 星期四

[Platform Builder] Error: Failed reading e32 structure in module

Problem:
When I try to make image on platform builder, I got an error message as title.
Error: Failed reading e32 structure in module <module_name>

Solution:
We can't placed a file that is NOT an *.exe or a *.dll in the MODULES section of a *.bib file.
We need to move that file to the FILES section of the *.bib


Reference:


2012年9月21日 星期五

[C++] Execute system call in command line.

Example for execute system call for Win32

#include "stdafx.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
    system( "cd c:\\windows\\system32");
    system( "notepad.exe C:\\1.txt");
    return 0;
}

Example for execute system call for WinCE

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    SHELLEXECUTEINFO ExecuteInfo;
    memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
 
    ExecuteInfo.cbSize       = sizeof(ExecuteInfo);
    ExecuteInfo.fMask        = 0;              
    ExecuteInfo.hwnd         = 0;              
    ExecuteInfo.lpVerb       = _T("open"); // Operation to perform
    ExecuteInfo.lpFile         = _T("\\storage card\\myBrowser.exe"); // Application name
    ExecuteInfo.lpParameters = _T("--shell"); // Additional parameters
    ExecuteInfo.lpDirectory  = 0; // Default directory
    ExecuteInfo.nShow        = SW_SHOW;
    ExecuteInfo.hInstApp     = 0;
 
    ShellExecuteEx(&ExecuteInfo);

    return 0;
}

Execute program in batch file

This is a simple sample of batch file to execute Notepad and open 1.txt file.


CD C:\Windows\System32
START notepad.exe C:\1.txt
EXIT


Reference:
http://blog.xuite.net/f8789/DCLoveEP/37390106

2012年9月20日 星期四

[Platform Builder] Launch AP when boot up in WinCE

I would like to launch an application when the WinCE device boot up, the AP I made is named 'test.exe'

Step 1:
Copy 'test.exe' along with its necessary dll and resource files into 'C:\WINCE700\platform\SDK_Name\FILES'
All files in the folder will be copy into the object folder (release/debug folder) after project build.


Step 2:
Modify file 'C:\WINCE700\platform\SDK_Name\FILES\platform.bib'
Add 'test.exe $(_FLATRELEASEDIR)\test.exe NK SH' in end of file, but before '; @CESYSGEN ENDIF CE_MODULES_DEVICE'

Step 2.1 (Option):
If you hope your .exe file locate at '\MyFiles\exe' folder, you should modify  'C:\WINCE700\platform\SDK_Name\FILES\platform.dat'

First, add folder into root, add script
root:-Directory("MyFiles")
then, add folder into MyFiles, add script 
Directory("\MyFiles"):-Directory("exe")
Final, add file into \MyFiles\exe, add script
Directory("\MyFiles\exe"):-File("test.exe", "\Windows\test.exe")

Step 3:
Modify file 'C:\WINCE700\platform\SDK_Name\FILES\platform.reg'
Add following statement in end of file, but before '; @CESYSGEN ENDIF CE_MODULES_DEVICE'
[HKEY_LOCAL_MACHINE\init]
"Launch300"="bsqBrowser.exe --shell"

If there is already exist [HKEY_LOCAL_MACHINE\init] , you can just append "Launch300"="bsqBrowser.exe --shell" after exist statement.
The number 300 is the order of initialization, you should give a number beyond exist statement. Avoid using the number smaller than 100 to prevent conflict to system program.

Step 4:
Build, make image and attach device.


Reference:
http://www.360doc.com/content/11/0308/23/4672432_99399478.shtml
http://www.wretch.cc/blog/awaysu/22149164
http://huenlil.pixnet.net/blog/post/23373616-%5B%E8%BD%89%5Dap-launch-flow-in-wince
http://msdn.microsoft.com/en-us/library/aa448442.aspx




2012年9月19日 星期三

Saturated Arithmetic

In general binary operation that 11111111(255)+00000001(1)=100000000(256)

The operation result will be 0 for 8 bit Adder, because the processor is 8 bits only.

If a processor support saturated arithmetic, 255+1 would be 255 (stop at max or min value), and it would not overflow or underflow.


Reference: 
http://www.techbang.com/posts/10678-fully-understand-arm-processors-cisc-and-risc-are-what-history-structure-a-see-through-the-computer-96-issues-cover-story-the-king?page=2

2012年9月13日 星期四

[Platform Builder] A script required for this install to complete could not be run.

Problem:
When I install the QFE 2011_Rollup for CE6.0 Platform Builder, I got an error message below.
There is a problem with this Windows Installer package. A script required for this install to complete could not be run. Contact your support personnel or package vendor.















Solve:
Right click on the msi, select the Compatibility tab, and check the box that says "Run this program in compatibility mode for". Leave the rest as is, and it should install after that. You may also need to do the same thing for some of the other QFE's.



























Reference:
http://bsquare.custhelp.com/app/answers/detail/a_id/733/~/installing-ce-6.0-product-update-rolllups-on-windows-7-and-vista


2012年9月4日 星期二

Python GTK+ 3 Tutorial

Just log the tutorial link.

http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html

Necessitas Project

Necessitas is a KDE community project aimed to provide an easy way to develop Qt apps on Android platform.

Please see below link for detail.

http://necessitas.kde.org/
http://www.youtube.com/watch?v=suPeZ7XC1xk

2012年8月25日 星期六

[C++] Sample for Using stdlib to implement Extend Quick Sort function

As last example, I use standard library to implement quick sort again.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>

void quickSortEx(int[], int, bool, int, int);
int cmp(const void* a, const void* b);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};

    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, true, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);

    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right)
{
    qsort(number, count, sizeof(number[0]), cmp);

    if (desc)
        std::reverse(number, number+count);
}

int cmp(const void* a, const void* b)
{
    const int x = *static_cast<const int*>(a);
    const int y = *static_cast<const int*>(b);

    if (x == y)
        return 0;

    return x > y ? 1 : -1;
}


Reference:
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
http://www.cplusplus.com/reference/algorithm/reverse/

2012年8月24日 星期五

[C++] A sample for Extended Quick Sort

I need to implement a function to sort items with specified ascending order.
I modify other's sample as below.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void quickSortEx(int[], int, bool, int, int);
void swap(int &x, int &y);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};
 
    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, false, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);
 
    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right) {
    if(left < right) {
        int i = left;
        int j = right + 1;

        while(1) {
            // To find the item should sort after 'left'
            while(i + 1 < count && (desc ? number[left] < number[++i] : number[++i] < number[left]));
            // To find the item should sort before 'left'
            while(j -1 > -1 && (desc ? number[left] > number[--j] : number[--j] > number[left])) ;
            if(i >= j)
                break;
            swap(number[i], number[j]);
        }

        swap(number[left], number[j]);

        quickSortEx(number, count, desc, left, j-1);
        quickSortEx(number, count, desc, j+1, right);
    }
}

void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

Reference:
http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/QuickSort1.htm
http://emn178.pixnet.net/blog/post/88613503-%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E6%B3%95(quick-sort)

2012年8月23日 星期四

[C++] Sample for String Compare

It is a simple sample for understanding how to implement a function to compare two string.

#include "stdafx.h"
#include <string.h>
#include <iostream>

using namespace std;

int codePointCompare(const char* c1, const char* c2)
{
 int l1 = strlen(c1);
 int l2 = strlen(c2);
        const unsigned lmin = l1 < l2 ? l1 : l2;
        unsigned pos = 0;
        while (pos < lmin && *c1 == *c2)
 {
             c1++;
             c2++;
             pos++;
        }

        if (pos < lmin)
             return (c1[0] > c2[0]) ? 1 : -1;

        if (l1 == l2)
             return 0;

 return (l1 > l2) ? 1 : -1;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char* c1 = new char[1024];
 char* c2 = new char[1024];
 cout << "please input first string:";
 cin >> c1;
 cout << "please input second string:";
 cin >> c2;

 cout << codePointCompare(c1, c2);
 return 0;
}


Reference:
http://trac.webkit.org/changeset/110822/trunk/Source/JavaScriptCore/wtf/text/StringImpl.cpp

2012年8月20日 星期一

[C++] Threading Sample

This is a simple sample for understanding of thread create in C++.

#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <stdio.h>

void myfunc(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE thd[2];
    DWORD tid;

    printf("Thead Start.\n");

    for (int i=0; i<2; i++)
    {
        thd[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)myfunc, (void*)i, 0, &tid);
        printf("Thread %d is start \n",tid);
    }


    Sleep(1000);

    printf("main is end \n");

    system("pause");
}

void myfunc(int n)
{
    int i;
    for(int i=0;i<5;i++){
        printf("Thread %d, index=%d\n", n, i);
        Sleep(1000);
    }
    printf("Thread %d is over \n", getpid());
}

Reference:
http://wuminfajoy.blogspot.tw/2010/10/c.html

2012年8月16日 星期四

[C++] Create GUID

You can create GUID by using CoCreateGuid API.
I copy example source code from my reference article for memo as below.


#include "stdafx.h"
#include <objbase.h>
#include <string>

using namespace std;

wstring GetGUID()
{
    _TUCHAR *guidStr = NULL;

    GUID *pguid = new GUID;

    CoCreateGuid(pguid);

    // Convert the GUID to a string
    UuidToString(pguid, (RPC_WSTR*)&guidStr);
    delete pguid;
    return wstring(guidStr);
}

int _tmain(int argc, _TCHAR* argv[])
{
wstring guid = GetGUID();
    wprintf(guid.c_str());
    return 0;
}



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms688568(v=vs.85).aspx
http://www.dotblogs.com.tw/alonstar/archive/2011/09/05/mfc_32bit_64bit.aspx

2012年8月12日 星期日

[MS SQL] Performance counter registry hive consistency check

To avoid meet the problem again, I memo the solution here.

While installing SQLServer 2008 on Windows 7 64bit - Traditional Chinese Version.
I got an error message told me "Performance counter registry hive consistency check".
It would not happen on English version OS.
Here is an article will help.
http://www.dotblogs.com.tw/lastsecret/archive/2010/06/14/15865.aspx

In addition, you should execute window update to download Visual Studio 2008 sp1 if you like to install SQL Server 2008 Management Studio. Otherwise you'll got error message as "Another version of Microsoft Visual Studio 2008 has been detected on this system that must be updated to SP1.  Please update all Visual Studio 2008 installations to SP1 level, by visiting Microsoft Update."



2012年7月19日 星期四

Certificate Store Operations

Example to get certificate from system.


#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);

int _tmain(int argc, _TCHAR* argv[])
{
    //--------------------------------------------------------------------
    // Copyright (C) Microsoft.  All rights reserved.
    // Declare and initialize variables.

    HCERTSTORE  hSystemStore;              // System store handle
    PCCERT_CONTEXT  pDesiredCert = NULL;   // Set to NULL for the first call to CertFindCertificateInStore
    PCCERT_CONTEXT  pCertContext;


    //-------------------------------------------------------------------
    // Open the My system store using CertOpenStore.

    if(hSystemStore = CertOpenStore(
         CERT_STORE_PROV_SYSTEM,            // System store will be a virtual store
         0,                                 // Encoding type not needed with this PROV
         NULL,                              // Accept the default HCRYPTPROV
         CERT_SYSTEM_STORE_CURRENT_USER,    // Set the system store location in the registry
         L"MY"))                            // Could have used other predefined  system stores including Trust, CA, or Root
    {
       printf("Opened the MY system store. \n");
    }
    else
    {
       MyHandleError( "Could not open the MY system store.");
    }



    //-------------------------------------------------------------------
    // Find the certificates in the system store. 
    while(pCertContextEnum=CertEnumCertificatesInStore(
          hSystemStore,
          pCertContextEnum)) // on the first call to the function, this parameter is NULL  on all subsequent                calls,  this parameter is the last pointer returned by the function
    {
        if(CertGetNameString(
           pCertContextEnum,
           CERT_NAME_SIMPLE_DISPLAY_TYPE,
           0,
           NULL,
           pszNameString,
           128))
        {
            printf("\nCertificate for %s \n",pszNameString);
        }
        else
           fprintf(stderr,"CertGetName failed. \n");
    } // End of while.



    //-------------------------------------------------------------------
    // Get a certificate that has the string "ninna.tw@gmail.com" in its subject. 

    if(pDesiredCert=CertFindCertificateInStore(
          hSystemStore,
          MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
          0,                            // No dwFlags needed 
          CERT_FIND_SUBJECT_STR,        // Find a certificate with a subject that matches the string in the next parameter
          L"ninna.tw@gmail.com",     // The Unicode string to be found in a certificate's subject
          NULL))                        // NULL for the first call to the function In all subsequent calls, it is the last pointer returned by the function
    {
      printf("The desired certificate was found. \n");
    }
    else
    {
       MyHandleError("Could not find the desired certificate.");
    }
    //-------------------------------------------------------------------
    // pDesiredCert is a pointer to a certificate with a subject that 
    // includes the string "ninna.tw@ gmail.com ", the string is 
    // passed as parameter #5 to the function.


    //-------------------------------------------------------------------
    // Close the stores.

    if(hSystemStore)
        CertCloseStore(
            hSystemStore,
            CERT_CLOSE_STORE_CHECK_FLAG);

    printf("All of the stores are closed. \n");

return 0;
}

//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function, to print an error message and exit 
// the program. 
// For most applications, replace this function with one 
// that does more extensive error reporting.

void MyHandleError(char *s)
{
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // end MyHandleError




You should add dependency for using static functions.
Right click on project -> Property -> Linker -> Input ->Additional Dependencies -> add crypt32.lib



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382037(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382363(v=vs.85).aspx

2012年5月25日 星期五

Watch Virtual / Physical Memory Usage

With previous article http://twnin.blogspot.com/2012/05/watch-process-memory-usage.html
There is another way to watch memory usage in program with win32 api.


    MEMORYSTATUS ms;
    ms.dwLength = sizeof(ms);
    GlobalMemoryStatus(&ms);

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    // Process-specific info (for calling process)
    wsprintf(chBuf,_T("TotalVirtual: %ld\n"), ms.dwTotalVirtual);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailVirtual: %ld\n"), ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // Process virtual memory usage (reserved + commit)
    wsprintf(chBuf,_T("UsageVirtual: %ld\n"), ms.dwTotalVirtual - ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // System info
    wsprintf(chBuf,_T("MemoryLoad: %ld\n"), ms.dwMemoryLoad);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("TotalPhys: %ld\n"), ms.dwTotalPhys);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPhys: %ld\n"), ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // System usage
    wsprintf(chBuf,_T("UsagePhys: %ld\n"), ms.dwTotalPhys - ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // Unused/unsupported
    wsprintf(chBuf,_T("TotalPageFile: %lu\n"), ms.dwTotalPageFile);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPageFile: %lu\n"), ms.dwAvailPageFile);
    OutputDebugString(chBuf);

Watch Process Memory Usage


To watch current process memory usage, we can use GetProcessMemoryInfo to get paging information.
It is sample code below.

    HANDLE hProcess = ::GetCurrentProcess();
    PROCESS_MEMORY_COUNTERS pmc;
    pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
    ::GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc));

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    wsprintf(chBuf,_T("PageFaultCount: 0x%08X\n"), pmc.PageFaultCount );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakWorkingSetSize: 0x%08X\n"),
    pmc.PeakWorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("WorkingSetSize: 0x%08X\n"), pmc.WorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PagefileUsage: 0x%08X\n"), pmc.PagefileUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakPagefileUsage: 0x%08X\n"),
    pmc.PeakPagefileUsage );
    OutputDebugString(chBuf);

    CloseHandle(hProcess);


Reference:
http://msdn.microsoft.com/en-us/library/ms682050(v=VS.85).aspx
http://blog.csdn.net/caimouse/article/details/1947575

Work around link error:
error lnk2019: unresolved external symbol _getprocessmemoryinfo@12 referenced in function
http://lanvu.wordpress.com/tag/error-lnk2019-unresolved-external-symbol-_getprocessmemoryinfo12-referenced-in-function/

It seems doesn't work on windows ce.
https://groups.google.com/group/microsoft.public.pocketpc.developer/browse_thread/thread/22c685d1df9ec17d/e05ad892433d56aa?lnk=raot&pli=1

Structure of PROCESS_MEMORY_COUNTERS
http://blog.csdn.net/zhsp1029/article/details/3162048