]> git.sur5r.net Git - cc65/blob - libsrc/common/strdup.s
Added mouse module from C64
[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         pha                     ; decsp will destroy A (but not X)
23         jsr     decsp4          ; Target/source
24
25 ; Store the pointer into the source slot
26
27         ldy     #1
28         txa
29         sta     (sp),y
30         pla           
31 .ifpc02
32         sta     (sp)
33 .else
34         dey
35         sta     (sp),y
36 .endif
37
38 ; Get length of S (which is still in a/x)
39
40         jsr     _strlen
41
42 ; Calculate strlen(S)+1 (the space needed)
43
44         add     #1
45         bcc     @L1
46         inx
47
48 ; Save the space we're about to allocate in ptr4
49
50 @L1:    sta     ptr4
51         stx     ptr4+1
52
53 ; Allocate memory. _malloc will not use ptr4
54
55         jsr     _malloc
56
57 ; Store the result into the target stack slot
58
59         ldy     #2
60         sta     (sp),y          ; Store low byte
61         sta     tmp1
62         txa                     ; Get high byte
63         iny
64         sta     (sp),y          ; Store high byte
65
66 ; Check for a NULL pointer
67
68         ora     tmp1
69         beq     OutOfMemory
70
71 ; Copy the string. memcpy will return the target string which is exactly
72 ; what we need here. It will also drop the allocated stack frame.
73
74         lda     ptr4
75         ldx     ptr4+1          ; Load size
76         jmp     _memcpy         ; Copy string, drop stackframe
77
78 ; Out of memory, return NULL (A = 0)
79
80 OutOfMemory:
81         tax
82         jmp     incsp4          ; Drop stack frame
83
84