]> git.sur5r.net Git - cc65/blob - libsrc/common/strdup.s
fa2d289c4e9e4c91b0395eb34a3e3ea1f81bd2c8
[cc65] / libsrc / common / strdup.s
1 ;
2 ; Ullrich von Bassewitz, 18.07.2000
3 ;
4 ; char* __fastcall__ strdup (const char* S);
5 ;
6 ; Note: The code knowns which zero page locations are used by malloc.
7 ;
8
9         .importzp       sp, tmp1, ptr4
10         .import         pushax, decsp4, incsp4
11         .import         _strlen, _malloc, _memcpy
12         .export         _strdup
13
14         .macpack        generic
15
16 _strdup:
17
18 ; Since we need some place to store the intermediate results, allocate a
19 ; stack frame. To make this somewhat more efficient, create the stackframe
20 ; as needed for the final call to the memcpy function.
21
22         jsr     decsp4          ; Target/source
23
24 ; Store the pointer into the source slot
25
26         ldy     #0
27         sta     (sp),y
28         iny
29         pha
30         txa
31         sta     (sp),y
32         pla
33
34 ; Get length of S (which is still in a/x)
35
36         jsr     _strlen
37
38 ; Calculate strlen(S)+1 (the space needed)
39
40         add     #1
41         bcc     @L1
42         inx
43
44 ; Save the space we're about to allocate in ptr4
45
46 @L1:    sta     ptr4
47         stx     ptr4+1
48
49 ; Allocate memory. _malloc will not use ptr4
50
51         jsr     _malloc
52
53 ; Store the result into the target stack slot
54
55         ldy     #2
56         sta     (sp),y          ; Store low byte
57         sta     tmp1
58         txa                     ; Get high byte
59         iny
60         sta     (sp),y          ; Store high byte
61
62 ; Check for a NULL pointer
63
64         ora     tmp1
65         beq     OutOfMemory
66
67 ; Copy the string. memcpy will return the target string which is exactly
68 ; what we need here. It will also drop the allocated stack frame.
69
70         lda     ptr4
71         ldx     ptr4+1          ; Load size
72         jmp     _memcpy         ; Copy string, drop stackframe
73
74 ; Out of memory, return NULL (A = 0)
75
76 OutOfMemory:
77         tax
78         jmp     incsp4          ; Drop stack frame
79
80