3/31/2010

function gurad and unguard

COPY from naver.com

flipcode - UT2K3 Exception Handling 를 보면 알겠지만, Unreal Engine에서는 guard / unguard라는 매크로를 이용해서 프로그램이 비정상적인 동작을 하여 종료하기 직전에 콜스택을 화면에 보여주고 우아하게 죽는다.

guard / unguard 매크로라는 것은 설정에 따라 다르게 정의되지만, 기본적으로는 다음과 같은 간단한 매크로인데...

#define guard(func) {static const TCHAR __FUNC_NAME__[]=TEXT(#func); try{
#define unguard }catch(TCHAR*Err){throw Err;}catch(...){appUnwindf(TEXT("%s"),__FUNC_NAME__); throw;}}

요지는 함수 이름을 저장해놨다가 exception이 발생하면 현재 함수 이름을 appUnwindf를 통해서 뿌리던가 하고 exception을 다시 던져서 상위 레벨의 catch가 또 처리하게 하는 것이다. (appUnwindf 구현은 알아서)

try / catch라는 것은 exception이 발생했을 때 무거운 것이지, 그냥 try에 들어가서 문제없이 빠져나올 때는 큰 문제가 안되기 때문에, 함수마다 사용해도 큰 문제는 없다. 문제가 되면 flipcode - Function Guarding처럼 guard의 레벨을 나눠서 사용해도 된다.

그러면 함수에서는

UBOOL Encode( FArchive& In, FArchive& Out )
{
guard(FCodecBWT::Encode);



return 0;

unguard;
}

이런 식으로 guard를 해주고 싶은 함수마다 guard / unguard 를 쓰고, guard 안에 함수 이름(또는 원하는 텍스트)을 채워야 하는데, 처음부터 이렇게 짰다면 모를까, 프로젝트 후반부에 이걸 적용하자! 라고 했다가는 감당이 안되는 것이다.

2005년 8월 17일, 조프의 E모 프로젝트의 서버에서 저 비슷한 것을 도입해야 한다는 결정이 나와서, 천장을 멍하니 보다가, guard/unguard의 구현은 ㅤㄱㅜㅊ은일 다해주는 석중에게 넘기긴 하였으나, 이제와서 저 입력을 매 함수마다 시키자니 사람이 시킬 짓이 아닌지라... 고민하던 와중에 석중이 기억해냈다.

__FUNCTION__

VC++에는 __FUNCTION__, 등등의 매크로가 있어서 __FILE__과 마찬가지로 __FUNCTION__이 함수 안에서 쓰일 때 함수 이름에 해당하는 문자열로 치환되는 것이다.1 비슷한 매크로가 두 개 쯤 더 있지만, 함수 이름이 얼마나 지독하게 나오냐 차이니 넘어가고...

좌우지간, 할 일은 두가지인데,

1. 매번 함수 이름을 채울 필요가 없게 하자

//#define guardfunc guard(__FUNCTION__) // 이건 안 될 수도
#define guardfunc {static const TCHAR __FUNC_NAME__[]=TEXT(__FUNCTION__); try{

끝.

UBOOL Encode( FArchive& In, FArchive& Out )
{
guardfunc;



return 0;

unguard;
}

이제는 이렇게만 해주면 알아서 함수 이름이 들어간다.

직접 문자열을 쓰고 싶을 때는 guard를 사용하면 된다.

2. 원하는 함수에 guardfunc / unguard를 쉽게 추가할 수 있도록 하자

비주얼 스튜디오는 나름 매크로라는 것을 지원한다.


현재 캐럿 위치에서 위쪽으로 앞에 빈 칸이 없는 '{'를 찾는다.
그 뒤에 '새 줄 + 탭 + guardfunc; + 새 줄'을 추가한다
그 위치에서 아래쪽으로 앞에 빈 칸이 없는 '}'를 찾는다.
그 앞에 '새 줄 + 탭 + unguard; + 새 줄'을 추가한다.
는 간단한 매크로를 짜는 것으로 해결했다. 함수의 시작과 끝을 제대로 인식해서 처리하면 좋겠다는 생각을 해봤으나 너무 귀찮았다.

비주얼 스튜디오는 나름 자동 인덴트를 해주고, 성격이 괴팍한 프로그래머가 아닌 다음에야 함수의 몸통을 둘러싸는 괄호 앞에 탭이나 공백을 주지는 않을터이니 이 정도면 그럭저럭 합리적인 해결책이라고 생각한다.

이 매크로를 단축키에 등록하고, 함수 안에서 단축키를 눌러주면 알아서 guardfunc;와 unguard;가 추가된다. (사실은 함수 밖에서 누르면 그 위에 있는 함수를 찾아서 그 함수에 추가한다)

guardfunc가 이미 있으면 새로 추가를 안하게 한다거나, 토글이 되게 한다거나 하면 아주 우아할 것 같지만, 없어도 크게 아쉽지 않은 기능이므로 생략.

매크로 코드는 다음과 같다.

Option Strict Off
Option Explicit Off

Imports EnvDTE
Imports System.Diagnostics

Public Module 뭔가이름을

Sub AddFunctionGuard()
'Description: Creates a guard block for the currently selected C/C++ function
Dim selection As TextSelection
Dim line As Integer

If (ActiveDocument() Is Nothing) Then
Exit Sub
End If
If ActiveDocument().Language = EnvDTE.Constants.dsCPP Then

selection = DTE.ActiveDocument.Selection()
line = selection.TextRanges.Item(1).StartPoint.Line
selection.GotoLine(line, True)

If selection.FindText(vbCrLf & "{", vsFindOptions.vsFindOptionsBackwards) Then
selection.EndOfLine()
selection.Insert(vbCrLf & vbTab & "GUARDFUNC;" & vbCrLf)

selection.Cancel()
If selection.FindText(vbCrLf & "}") Then
selection.StartOfLine()
selection.Text = vbCrLf & vbTab & "UNGUARD;" & vbCrLf
End If

' GUARDFUNC가 들어갔을테니 2줄 더해준다
selection.GotoLine(line + 2)
End If

End If
End Sub


End Module



--------------------------------------------------------------------------------

없진 않은데. 클래스내 멤버펑션 선언에서 바디까지 써버린다던가... ─ㄷㅋ 2005-8-18 15:24
인라인 처리할 정도라면 guard/unguard를 안쓰거나. 직접 쓰거나. 아쉬우면 매크로를 고쳐주삼. ─조프 2005-8-18 15:31
우린 노가다로 이미 다 다 넣어서 ─ㄷㅋ 2005-8-18 15:55
답글달기
이름 기본으로 한 단락 들여쓰기입니다. 콜론(:)을 붙이면 더 들여쓸 수 있습니다.

Homepage :


regexp를 한 번 거하게 써서 코드를 뒤엎어봄이? 반쯤은 파서가 되어야 하겠지만... 누가 하루쯤 달라붙으면 충분하리라 생각하는데. ─라슈펠 2005-8-18 17:52
위에는 try...catch가 가볍다고 썼지만, 그렇다고 공짜로 돌아가는게 아니기 때문에 모든 함수에 적용시키는 것도 문제가 있어서.
그리고 우리 서버는 try...catch가 아니라 다른 식으로 구현해서 쓸 것이기 때문에. 어쨌든. 원하는 함수에 추가하는 기능으로 충부함. ─조프 2005-8-18 18:04
regexp 로 하면, ^\{ 를 {\n\tguardfunc 로 바꿔주고 ^\} 를 \tungurad\n} 로 바꿔주면 되겠군요... ─쌀밥 2005-9-8 17:51
첫번째 단락과 같은 이유로 헤더 파일에는 적용을 못하고, cpp 파일에서도 네임스페이스의 {} 쌍, enum의 {} 쌍 등등에까지 끼어들 수 있습니다. 그래서 자동은 포기. ─조프 2005-9-8 18:35
\)\s*\n\{ 를 )\n{\n\tguardfunc 으로 ^\}\n 을 \tunguard\n}\n 으로 바꾸는게 더 좋은거 같네요... ─쌀밥 2005-9-8 18:55
해보니 왠만한건 다 통과 되는데
void myFunc () {
}
이런건 안되네요;;;; vc++ 말고 vi 에서 하면 ^([^\{]+\)\s*\n\{\n) 를 \1\nguardfunc\n 으로 될거 같은데... vc++ 에서는 참조(\1, \2 등등..)가 안되는듯;; ─쌀밥 2005-9-8 19:05
답글달기
이름 기본으로 한 단락 들여쓰기입니다. 콜론(:)을 붙이면 더 들여쓸 수 있습니다.

Homepage :


그리고 guardfunc; <...> unguard; 형태보다는 guardfunc { <...> } unguard;형태를 좋아하지만... 어차피 내 취향과는 별 관계 없는 일이겠지? ; ─라슈펠 2005-8-18 17:55
guard / unguard 매크로의 구현을 보면
void functionname()
guardfunc
{
}
unguard;
이라고 해도 문제 없을 것 같은데? guard와 unagurd가 {}를 포함하고 있으니까. 그렇게 쓰고 싶으면 비베 스크립트를 조금 고쳐서 쓰면 되겠지. ─조프 2005-8-18 18:06
아니 구현 문제가 아니라 코딩 스타일 문제... ; {}가 있어줘야 어디부터 어디까지가 guard영역인지 보이지 않겠나. ─라슈펠 2005-8-18 18:08
익숙해지면 괜찮아. 그리고 중첩해서 쓰기도 하지만 대부분의 경우는 함수를 통째로 감싸는 용도로 쓰기 땜시; ─조프 2005-8-18 18:51
답글달기

3/21/2010

Linux 2.2 Framebuffer Device Programming Tutorial

Linux 2.2 Framebuffer Device Programming Tutorial
This is a quick document I produced while figuring out how to use the framebuffer device to produce graphics on the Linux console. I don't claim to be an expert in this area, but when I looked for a general guide to doing this, I found absolutely nothing, except the header file

Therefore, this is meant to be a jump-start guide for those who want to begin using graphics in the linux console. Hopefully someone out there will write a decent graphical browser, so I don't have to start up X every time I want to surf!

As always, no warranty, express or implied...etc. Give me a break, I took my first look at this device less than 24 hours ago! Any corrections, money, gifts, etc. (I wish!), just contact me
You may freely distribute this document, as long as you do not change it in any way, and credit me as author. In particular, I encourage Linux distributions to include this in their packages, as I feel there isn't half as much programming information in most distributions as there ought to be. Copyright James Dabell, May 1999.
This document was last updated June 11th, 1999. (Corrections from Joerg Beyer & Ian Thompson-Bell)

Part One:

First of all, configure your system for the framebuffer console device. It may come in handy. Note that the device is only available for graphics cards that implement VESA 2.0. Fortunately, virtually all recent cards out there do this.

When you have got high-res textmodes, then you can start experimenting. You will have a device /dev/fb0 that you can look at like any normal file. To take a screenshot, all you have to do is

cat /dev/fb0 > ~/sshot

And you will have a pretty big file with the contents of your graphics card's memory inside. Now, if you clear the screen, and type
cat ~/sshot > /dev/fb0

You should have a display that looks exactly like before. Of course, the second you start typing the display reverts to normal.
Part Two:

So now, we can move on to using the device in a C program. Take a look at the following code:

#include
#include
#include
int main()
{
int fbfd = 0;

fbfd = open("/dev/fb0", O_RDWR);
if (!fbfd) {
printf("Error: cannot open framebuffer device.\n");
exit(1);
}
printf("The framebuffer device was opened successfully.\n");

close(fbfd);
return 0;
}

All in all, a pretty simple program. We open the framebuffer device file using the low-level open(), because the buffered, higher level fopen() is unsuitable for our needs.
Next, we test the file descriptor to make sure that we were successful, and print a message out that tells the user what happened.
Note that if you #include , then you will be able to find out exactly why the open() call fails. Check the man page for open() for more information on this
Finally, we clean up by closing the file descriptor and returning.
Part Three:

Using the newly created file descriptor, we can perform operations on the framebuffer with the ioctl() function. This function is used to talk to special device files in ways that are particular to that device. In this case, we can use it to obtain information on the video card. We can also use the file descriptor to map the file into memory, and use a pointer to access it, which is more efficient and easier on us. This is done using the mmap() function. If you haven't used this before, here is some sample code:

#include
#include
#include
#include
#include

int main()
{
int fbfd = 0;
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
long int screensize = 0;
char *fbp = 0;

fbfd = open("/dev/fb0", O_RDWR);
if (!fbfd) {
printf("Error: cannot open framebuffer device.\n");
exit(1);
}
printf("The framebuffer device was opened successfully.\n");

if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) {
printf("Error reading fixed information.\n");
exit(2);
}

if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
printf("Error reading variable information.\n");
exit(3);
}

screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;
fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0);
if ((int)fbp == -1) {
printf("Error: failed to map framebuffer device to memory.\n");
exit(4);
}
printf("The framebuffer device was mapped to memory successfully.\n");

munmap(fbp, screensize);
close(fbfd);
return 0;
}

As you can see, we have to #include an extra header file to deal with mmap(). We use the information returned by the ioctl()s to figure out how much memory to map. The members of fb_var_screeninfo that are used are xres, yres, and bits_per_pixel.
Note that there is also what is known as the virtual screen size, which can be utilised for scrolling, etc, but that is beyond the scope of this document. However, if you are planning on using scrolling, you will probably want to use xres_virtual and yres_virtual to calculate how much memory to map.
Finally, remember to munmap() the memory you have mapped for use with the framebuffer.
Part Four:

In this section we finally get to plot a pixel on the screen. First of all, we need to know in what format we should put the data. As it is the most common, and also the only type I have access to, I will be talking about the type of framebuffer that utilises packed pixels. All that is necessary to put a pixel on the screen, is to put bytes corresponding to the colours blue, green, red and transparency, in that order, at the correct location in memory, starting at 0 for x = 0, y = 0, and increasing by four bytes for every x, and y * the length of the line in bytes for every y. Standard graphics stuff; people used to the good ol' days back in mode 13h programming in DOS will catch on quickly. Anyway, here's the code:

#include
#include
#include
#include
#include

int main()
{
int fbfd = 0;
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
long int screensize = 0;
char *fbp = 0;
int x = 0, y = 0;
long int location = 0;

/* Open the file for reading and writing */
fbfd = open("/dev/fb0", O_RDWR);
if (!fbfd) {
printf("Error: cannot open framebuffer device.\n");
exit(1);
}
printf("The framebuffer device was opened successfully.\n");

/* Get fixed screen information */
if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) {
printf("Error reading fixed information.\n");
exit(2);
}

/* Get variable screen information */
if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
printf("Error reading variable information.\n");
exit(3);
}

/* Figure out the size of the screen in bytes */
screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;

/* Map the device to memory */
fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED,
fbfd, 0);
if ((int)fbp == -1) { printf("Error: failed to map
framebuffer device to memory.\n"); exit(4);
}
printf("The framebuffer device was mapped to memory successfully.\n");

x = 100; y = 100; /* Where we are going to put the pixel */

/* Figure out where in memory to put the pixel */
location = (x+vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
(y+vinfo.yoffset) * finfo.line_length;

*(fbp + location) = 100; /* Some blue */
*(fbp + location + 1) = 15; /* A little green */
*(fbp + location + 2) = 200; /* A lot of red */
*(fbp + location + 3) = 0; /* No transparency */

munmap(fbp, screensize);
close(fbfd);
return 0;
}

Now that you know how to plot a pixel, it becomes a trivial matter to write functions to draw lines, boxes, windows, etc. Hopefully, by now you are well on your way to writing that web browser for me - consider it payment for this tutorial ;).

3/15/2010

SDL build on Linux ( Fedora11 ) ubuntu x86


./configure

make

UltraEdit Lua Word Files Fixed Block Comment

울트라 에디터 사용시 루아 파일 블록 지정 코맨트 설정을 해주어야 제대로 볼 수 있다.

this is does not correct action block comment ...

--[[

--]]

/L20"Lua" Line Comment Num = 3-- Escape Char = \ Block Comment On = --[[ Block Comment Off = ]] String Chars = "' File Extensions = LUA BIN
/Delimiters = ~!@%^&*()-+=|\/{}[]:;"'<> , .?
/Function String = "%[a-zA-Z]*)"
/C1 "key words"
and
do
else elseif end
function
if
local
nil not
or
repeat return
then
until
while
/C2
abs acos appendto ascii asin assert atan atan2
call ceil clock collectgarbage copytagmethods cos
date deg dofile dostring
error execute exit
floor foreach foreachvar format frexp
getbinmethod getenv getglobal gettagmethod gsub
ldexp log log10
max min mod
newtag next nextvar
print
rad random randomseed rawgetglobal rawgettable rawsetglobal rawsettable read
readfrom remove rename
seterrormethod setglobal setlocale settag settagmethod sin sqrt strbyte
strchar strfind strlen strlower strrep strsub strupper
tag tan tmpname tonumber tostring type
write writeto
/C3
$debug
$else
$end
$endinput
$if
$ifnot
$nodebug
/C4
PI
_INPUT _OUTPUT _STDERR _STDIN _STDOUT
/C5
+
-
*
// /
^
<
>
=
~
%
.
:
/C6
;
,
(
)
{
}
[
]
/C7
cgi cgilua cgilua_url char2hexa chdir
dbluaerrorfb dblua_escape decode default_script
encodecgi encodetable escape
filetype
getvalue
hexa hexa2char html_mask
includehtml insertfield
lua_mask
maketable map mkurl
nopipe
preprocess
redirect relativeurl relative_url
saveluavar savestate script_path script_pdir script_vdir stateerrormethod
statefile stdin strsplit
unescape
/C8
DBClose DBExec DBOpen DBRow