-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpluginlib.c
More file actions
1962 lines (1690 loc) · 63.3 KB
/
pluginlib.c
File metadata and controls
1962 lines (1690 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* pluginlib.c - PluginLib shim for CodeWarrior compiler DLLs
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <windows.h>
#include "cw_types.h"
#include "host_ctx.h"
CWPluginContext g_context = NULL;
#define LOG(fmt, ...) do { if (g_context && g_context->verbose) { fprintf(stderr, "[PluginLib" STRINGIFY(PLUGINLIB_VER) "] " fmt "\n", ##__VA_ARGS__); fflush(stderr); } } while(0)
#define STUB(name) LOG("STUB: %s called", name)
/* Forward declarations */
CW_CALLBACK CWGetMemHandleSize(CWPluginContext context, CWMemHandle handle, SInt32* size);
CW_CALLBACK CWLockMemHandle(CWPluginContext context, CWMemHandle handle, Boolean moveHi, void** ptr);
CW_CALLBACK CWUnlockMemHandle(CWPluginContext context, CWMemHandle handle);
/*
* Convert line endings to \r (Mac convention) in-place.
* Matches MWCC FixTextHandle(): \n -> \r, \r\n -> \r\n (unchanged).
* Buffer can only shrink (standalone \n replaced by \r, same length;
* \r\n pairs are left alone). Returns new size.
*/
static SInt32 fix_text_line_endings(char* buf, SInt32 size) {
SInt32 out = 0;
for (SInt32 i = 0; i < size; i++) {
if (buf[i] == '\r') {
buf[out++] = '\r';
if (i + 1 < size && buf[i + 1] == '\n') {
buf[out++] = '\n';
i++; /* skip the \n of \r\n pair */
}
} else if (buf[i] == '\n') {
buf[out++] = '\r'; /* convert standalone \n to \r */
} else {
buf[out++] = buf[i];
}
}
buf[out] = '\0';
return out;
}
/*
* Read a file into a malloc'd buffer and convert line endings to \r.
* Returns NULL on failure. Sets *out_size to the converted size.
*/
static char* read_and_fix_file(const char* path, SInt32* out_size) {
FILE* f = fopen(path, "rb");
if (!f) return NULL;
fseek(f, 0, SEEK_END);
long size = ftell(f);
fseek(f, 0, SEEK_SET);
char* buf = (char*)malloc(size + 1);
if (!buf) { fclose(f); return NULL; }
fread(buf, 1, size, f);
buf[size] = '\0';
fclose(f);
*out_size = fix_text_line_endings(buf, (SInt32)size);
return buf;
}
static void copy_cstr(char* dst, size_t dst_size, const char* src) {
size_t i = 0;
if (!dst || dst_size == 0) return;
if (!src) {
dst[0] = '\0';
return;
}
while (i + 1 < dst_size && src[i]) {
dst[i] = src[i];
i++;
}
dst[i] = '\0';
}
static void cwfilespec_from_cpath(CWFileSpec* spec, const char* path) {
if (!spec) return;
if (!path) path = "";
#if PLUGINLIB_VER == 2
size_t len;
memset(spec, 0, sizeof(*spec));
len = strlen(path);
if (len > 255) len = 255;
spec->name[0] = (UInt8)len;
if (len > 0) {
memcpy(spec->name + 1, path, len);
}
#else
copy_cstr(spec->path, MAX_PATH, path);
#endif
}
static void cwfilespec_to_cpath(const CWFileSpec* spec, char* out, size_t out_size) {
if (!out || out_size == 0) return;
out[0] = '\0';
if (!spec) return;
#if PLUGINLIB_VER == 2
size_t len = spec->name[0];
if (len > 255) len = 255;
if (len + 1 > out_size) len = out_size - 1;
if (len > 0) {
memcpy(out, spec->name + 1, len);
}
out[len] = '\0';
#else
copy_cstr(out, out_size, spec->path);
#endif
}
static void cw_filename_arg_to_cpath(const char* filename, char* out, size_t out_size) {
if (!out || out_size == 0) return;
out[0] = '\0';
if (!filename) return;
#if PLUGINLIB_VER == 2
{
UInt8 len = (UInt8)filename[0];
if (len > 0 && len < out_size && memchr(filename + 1, '\0', len) == NULL) {
memcpy(out, filename + 1, len);
out[len] = '\0';
return;
}
}
#endif
copy_cstr(out, out_size, filename);
}
static int join_path(char* out, size_t out_size, const char* dir, const char* leaf) {
int n;
if (!out || out_size == 0 || !dir || !leaf) return 0;
n = snprintf(out, out_size, "%s/%s", dir, leaf);
return n > 0 && (size_t)n < out_size;
}
static void get_directory(const char* filepath, char* dir, size_t dirsize) {
char* sep;
copy_cstr(dir, dirsize, filepath);
sep = strrchr(dir, '\\');
if (!sep) sep = strrchr(dir, '/');
if (sep) *(sep + 1) = '\0';
else copy_cstr(dir, dirsize, ".");
}
static int is_full_path(const char* path) {
if (!path || !path[0]) return 0;
if ((isalpha((unsigned char)path[0]) && path[1] == ':') ||
path[0] == '\\' || path[0] == '/')
return 1;
return 0;
}
static int ensure_file_record_capacity(CWPluginContext ctx) {
HostFileRecord* recs;
SInt32 new_cap;
if (ctx->fileRecordCount < ctx->fileRecordCap) return 1;
new_cap = (ctx->fileRecordCap > 0) ? (ctx->fileRecordCap * 2) : 64;
recs = (HostFileRecord*)realloc(ctx->fileRecords, (size_t)new_cap * sizeof(HostFileRecord));
if (!recs) return 0;
ctx->fileRecords = recs;
ctx->fileRecordCap = new_cap;
return 1;
}
static void record_file_id(CWPluginContext ctx, short file_id, const char* path, Boolean is_system) {
for (SInt32 i = 0; i < ctx->fileRecordCount; i++) {
if (ctx->fileRecords[i].fileID == file_id) {
copy_cstr(ctx->fileRecords[i].path, MAX_PATH, path);
ctx->fileRecords[i].isSystem = is_system;
return;
}
}
if (!ensure_file_record_capacity(ctx)) return;
ctx->fileRecords[ctx->fileRecordCount].fileID = file_id;
ctx->fileRecords[ctx->fileRecordCount].isSystem = is_system;
copy_cstr(ctx->fileRecords[ctx->fileRecordCount].path, MAX_PATH, path);
ctx->fileRecordCount++;
}
static const char* lookup_file_id_path(const CWPluginContext ctx, short file_id) {
for (SInt32 i = 0; i < ctx->fileRecordCount; i++) {
if (ctx->fileRecords[i].fileID == file_id)
return ctx->fileRecords[i].path;
}
return NULL;
}
static void normalize_include_path(const char* path, char* out, size_t out_size) {
if (!out || out_size == 0) return;
out[0] = '\0';
if (!path || !path[0]) return;
copy_cstr(out, out_size, path);
for (size_t i = 0; out[i]; i++) {
if (out[i] == '\\') out[i] = '/';
out[i] = (char)tolower((unsigned char)out[i]);
}
}
static int ensure_include_record_capacity(CWPluginContext ctx) {
HostIncludeRecord* recs;
SInt32 new_cap;
if (ctx->includeRecordCount < ctx->includeRecordCap) return 1;
new_cap = (ctx->includeRecordCap > 0) ? (ctx->includeRecordCap * 2) : 64;
recs = (HostIncludeRecord*)realloc(ctx->includeRecords, (size_t)new_cap * sizeof(HostIncludeRecord));
if (!recs) return 0;
ctx->includeRecords = recs;
ctx->includeRecordCap = new_cap;
return 1;
}
static Boolean was_include_loaded(const CWPluginContext ctx, const char* path) {
char normalized[MAX_PATH];
if (!ctx || !path || !path[0]) return FALSE;
normalize_include_path(path, normalized, sizeof(normalized));
if (!normalized[0]) return FALSE;
for (SInt32 i = 0; i < ctx->includeRecordCount; i++) {
if (strcmp(ctx->includeRecords[i].path, normalized) == 0)
return TRUE;
}
return FALSE;
}
static void mark_include_loaded(CWPluginContext ctx, const char* path) {
char normalized[MAX_PATH];
if (!ctx || !path || !path[0]) return;
normalize_include_path(path, normalized, sizeof(normalized));
if (!normalized[0]) return;
for (SInt32 i = 0; i < ctx->includeRecordCount; i++) {
if (strcmp(ctx->includeRecords[i].path, normalized) == 0)
return;
}
if (!ensure_include_record_capacity(ctx)) return;
copy_cstr(ctx->includeRecords[ctx->includeRecordCount].path, MAX_PATH, normalized);
ctx->includeRecordCount++;
}
static CWResult load_file_for_include(const char* path, CWFileInfo* fileinfo,
CWPluginContext ctx, Boolean suppressload, Boolean is_system)
{
SInt32 size;
char* buf = NULL;
Boolean already_included;
already_included = was_include_loaded(ctx, path);
if (!suppressload) {
if (already_included && ctx->forceIncludeOnce) {
/* Match mwccps2 -once behavior even when cc_mips.dll doesn't
* honor #pragma once on/off toggles from the frontend. */
buf = (char*)malloc(1);
if (!buf) return cwErrOutOfMemory;
buf[0] = '\0';
fileinfo->filedata = buf;
fileinfo->filedatalength = 0;
} else {
buf = read_and_fix_file(path, &size);
if (!buf) return cwErrFileNotFound;
fileinfo->filedata = buf;
fileinfo->filedatalength = size;
}
} else {
if (!is_full_path(path) && !strchr(path, '/')) {
/* For suppress-load checks, existence still matters for leaf names. */
FILE* f = fopen(path, "rb");
if (!f) return cwErrFileNotFound;
fclose(f);
} else {
FILE* f = fopen(path, "rb");
if (!f) return cwErrFileNotFound;
fclose(f);
}
fileinfo->filedata = NULL;
fileinfo->filedatalength = 0;
}
fileinfo->filedatatype = cwFileTypeText;
fileinfo->fileID = ctx->nextFileID++;
cwfilespec_from_cpath(&fileinfo->filespec, path);
fileinfo->alreadyincluded = already_included;
fileinfo->recordbrowseinfo = FALSE;
record_file_id(ctx, fileinfo->fileID, path, is_system);
if (!suppressload) {
mark_include_loaded(ctx, path);
}
get_directory(path, ctx->lastIncludeDir, sizeof(ctx->lastIncludeDir));
return cwNoErr;
}
static CWResult try_load_include_recursive(const char* dir, const char* filename,
CWFileInfo* fileinfo, CWPluginContext ctx,
Boolean suppressload, Boolean is_system, int depth)
{
char pattern[MAX_PATH];
char candidate[MAX_PATH];
WIN32_FIND_DATAA ffd;
HANDLE h;
if (depth > 32) return cwErrFileNotFound;
if (!join_path(pattern, sizeof(pattern), dir, "*")) return cwErrFileNotFound;
h = FindFirstFileA(pattern, &ffd);
if (h == INVALID_HANDLE_VALUE) return cwErrFileNotFound;
do {
char child[MAX_PATH];
CWResult r;
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue;
if (!join_path(child, sizeof(child), dir, ffd.cFileName)) continue;
if (!join_path(candidate, sizeof(candidate), child, filename)) continue;
r = load_file_for_include(candidate, fileinfo, ctx, suppressload, is_system);
if (r == cwNoErr) {
FindClose(h);
return cwNoErr;
}
if (try_load_include_recursive(child, filename, fileinfo, ctx, suppressload, is_system, depth + 1) == cwNoErr)
{
FindClose(h);
return cwNoErr;
}
} while (FindNextFileA(h, &ffd));
FindClose(h);
return cwErrFileNotFound;
}
/*
* Helper: try to load a file from a directory path + filename.
* If recursive is TRUE, scan subdirectories too (MWCC -ir behavior).
*/
static CWResult try_load_include(const char* dir, const char* filename,
CWFileInfo* fileinfo, CWPluginContext ctx, Boolean suppressload, Boolean recursive,
Boolean is_system)
{
char fullpath[MAX_PATH];
if (!join_path(fullpath, sizeof(fullpath), dir, filename)) return cwErrFileNotFound;
if (load_file_for_include(fullpath, fileinfo, ctx, suppressload, is_system) == cwNoErr) {
return cwNoErr;
}
if (recursive) {
return try_load_include_recursive(dir, filename, fileinfo, ctx, suppressload, is_system, 0);
}
return cwErrFileNotFound;
}
/* ============================================================
* CW Plugin Core
* ============================================================ */
CW_CALLBACK CWGetPluginRequest(CWPluginContext context, SInt32* request) {
g_context = context;
LOG("CWGetPluginRequest(context=%p)", context);
if (!context || !request) return cwErrInvalidParameter;
*request = context->request;
LOG(" request=%d", *request);
return cwNoErr;
}
CW_CALLBACK CWDonePluginRequest(CWPluginContext context, CWResult resultCode) {
LOG("CWDonePluginRequest(result=%d)", resultCode);
return cwNoErr;
}
CW_CALLBACK CWGetAPIVersion(CWPluginContext context, SInt32* version) {
LOG("CWGetAPIVersion");
if (!context || !version) return cwErrInvalidParameter;
*version = context->apiVersion;
return cwNoErr;
}
CW_CALLBACK CWGetProjectFile(CWPluginContext context, CWFileSpec* projectSpec) {
LOG("CWGetProjectFile");
if (!context || !projectSpec) return cwErrInvalidParameter;
memset(projectSpec, 0, sizeof(*projectSpec)); // TODO: stub
return cwNoErr;
}
CW_CALLBACK CWGetProjectFileCount(CWPluginContext context, SInt32* count) {
LOG("CWGetProjectFileCount");
if (!context || !count) return cwErrInvalidParameter;
*count = context->numFiles;
return cwNoErr;
}
CW_CALLBACK CWGetOutputFileDirectory(CWPluginContext context, CWFileSpec* outputFileDirectory) {
char outdir[MAX_PATH];
LOG("CWGetOutputFileDirectory");
if (!context || !outputFileDirectory) return cwErrInvalidParameter;
if (context->outputFile[0]) {
get_directory(context->outputFile, outdir, sizeof(outdir));
} else {
DWORD n = GetCurrentDirectoryA(sizeof(outdir), outdir);
if (n == 0 || n >= sizeof(outdir)) return cwErrRequestFailed;
}
cwfilespec_from_cpath(outputFileDirectory, outdir);
return cwNoErr;
}
CW_CALLBACK CWGetFileInfo(CWPluginContext context, SInt32 whichfile, Boolean checkFileLocation,
CWProjectFileInfo* fileinfo)
{
const char* path = NULL;
LOG("CWGetFileInfo(whichfile=%d)", (int)whichfile);
if (!context || !fileinfo) return cwErrInvalidParameter;
memset(fileinfo, 0, sizeof(*fileinfo));
fileinfo->fileID = (short)whichfile;
fileinfo->gendebug = context->debugInfo ? TRUE : FALSE;
(void)checkFileLocation;
if (whichfile == context->whichFile && context->sourceFile[0]) {
path = context->sourceFile;
} else {
path = lookup_file_id_path(context, (short)whichfile);
}
if (path && path[0]) {
cwfilespec_from_cpath(&fileinfo->filespec, path);
GetSystemTimeAsFileTime(&fileinfo->moddate);
return cwNoErr;
}
return cwErrUnknownFile;
}
CW_CALLBACK CWGetOverlay1GroupsCount(CWPluginContext context, SInt32* count) {
LOG("CWGetOverlay1GroupsCount");
if (!context || !count) return cwErrInvalidParameter;
*count = 0;
return cwNoErr;
}
CW_CALLBACK CWGetOverlay1GroupInfo(CWPluginContext context, SInt32 whichgroup,
CWOverlay1GroupInfo* groupinfo)
{
LOG("CWGetOverlay1GroupInfo(whichgroup=%d)", (int)whichgroup);
if (!context || !groupinfo) return cwErrInvalidParameter;
memset(groupinfo, 0, sizeof(*groupinfo));
return cwErrUnknownSegment;
}
CW_CALLBACK CWGetOverlay1Info(CWPluginContext context, SInt32 whichgroup, SInt32 whichoverlay,
CWOverlay1Info* overlayinfo)
{
LOG("CWGetOverlay1Info(whichgroup=%d, whichoverlay=%d)", (int)whichgroup, (int)whichoverlay);
if (!context || !overlayinfo) return cwErrInvalidParameter;
memset(overlayinfo, 0, sizeof(*overlayinfo));
return cwErrUnknownSegment;
}
CW_CALLBACK CWGetOverlay1FileInfo(CWPluginContext context, SInt32 whichgroup,
SInt32 whichoverlay, SInt32 whichoverlayfile, CWOverlay1FileInfo* fileinfo)
{
LOG("CWGetOverlay1FileInfo(whichgroup=%d, whichoverlay=%d, whichoverlayfile=%d)",
(int)whichgroup, (int)whichoverlay, (int)whichoverlayfile);
if (!context || !fileinfo) return cwErrInvalidParameter;
memset(fileinfo, 0, sizeof(*fileinfo));
return cwErrUnknownSegment;
}
CW_CALLBACK CWAlert(CWPluginContext context, const char* msg1, const char* msg2,
const char* msg3, const char* msg4)
{
LOG("CWAlert");
if (!context) return cwErrInvalidParameter;
if (msg1) fprintf(stderr, "%s", msg1);
if (msg2) fprintf(stderr, " %s", msg2);
if (msg3) fprintf(stderr, " %s", msg3);
if (msg4) fprintf(stderr, " %s", msg4);
if (msg1 || msg2 || msg3 || msg4) fprintf(stderr, "\n");
return cwNoErr;
}
CW_CALLBACK CWShowStatus(CWPluginContext context, const char* line1, const char* line2) {
if (line1) fprintf(stderr, "%s", line1);
if (line2) fprintf(stderr, " %s", line2);
if (line1 || line2) fprintf(stderr, "\n");
return cwNoErr;
}
CW_CALLBACK CWUserBreak(CWPluginContext context) {
STUB("CWUserBreak");
return cwNoErr;
}
/*
* The compiler reports line numbers in a shifted 16.16 form
* (e.g. line 2 arrives as 0x00020000). Normalize before printing.
*/
static SInt32 normalize_message_line(SInt32 raw_line) {
UInt32 line = (UInt32)raw_line;
if ((line & 0xFFFFu) == 0 && (line >> 16) != 0)
return (SInt32)(line >> 16);
return raw_line;
}
CW_CALLBACK CWReportMessage(CWPluginContext ctx,
const CWMessageRef* msgRef, const char* line1, const char* line2,
short errorlevel, SInt32 errorNumber)
{
const char* level_str = "info";
SInt32 linenumber = 0;
char source_path[MAX_PATH];
source_path[0] = '\0';
if (msgRef) {
const CWMessageRef* msg = msgRef;
linenumber = normalize_message_line(msg->linenumber);
cwfilespec_to_cpath(&msg->sourcefile, source_path, sizeof(source_path));
}
if (errorlevel == messagetypeWarning) {
level_str = "warning";
ctx->numWarnings++;
} else if (errorlevel == messagetypeError) {
level_str = "error";
ctx->numErrors++;
}
if (source_path[0]) {
fprintf(stderr, "%s:%d: %s: ", source_path, (int)linenumber, level_str);
} else {
fprintf(stderr, "%s: ", level_str);
}
if (line1) fprintf(stderr, "%s", line1);
if (line2) fprintf(stderr, "\n %s", line2);
fprintf(stderr, "\n");
return cwNoErr;
}
CW_CALLBACK CWSetModDate(CWPluginContext ctx,
const CWFileSpec* filespec, CWFileTime* moddate, Boolean isGenerated)
{
STUB("CWSetModDate");
return cwNoErr;
}
CW_CALLBACK CWCreateNewTextDocument(CWPluginContext ctx,
const CWNewTextDocumentInfo* docinfo)
{
LOG("CWCreateNewTextDocument");
/* Used for preprocessor output (-E mode) */
if (!ctx || !docinfo) return cwErrInvalidParameter;
if (ctx->preprocess == 2 && !ctx->preprocess) {
/*
* MWCC dependency pass (-M/-MM/-make) runs with preprocess mode 2.
* This pass is for dependency collection, not text emission.
*/
return cwNoErr;
}
if (docinfo->text) {
void* ptr = NULL;
SInt32 size = 0;
SInt32 emitted = 0;
CWGetMemHandleSize(ctx, docinfo->text, &size);
CWLockMemHandle(ctx, docinfo->text, FALSE, &ptr);
if (ptr) {
/* Fall back to strlen if size is unknown (e.g. handle allocated
* internally by the DLL without going through COS_NewHandle) */
if (size <= 0)
size = (SInt32)strlen((const char*)ptr);
/* Strip trailing null terminator if present (matches MWCC) */
if (size > 0 && ((const char*)ptr)[size - 1] == '\0')
size--;
if (size > 0) {
/*
* Normalize line endings: \r\n -> \n, \r -> \n.
* The DLL uses Mac-convention \r for line endings.
* Matches MWCC reference SendHandleToFile() behavior.
*/
const char* p = (const char*)ptr;
const char* end = p + size;
while (p < end) {
const char* lineEnd = p;
while (lineEnd < end && *lineEnd != '\r' && *lineEnd != '\n')
lineEnd++;
if (lineEnd > p) {
fwrite(p, 1, lineEnd - p, stdout);
emitted += (SInt32)(lineEnd - p);
}
fputc('\n', stdout);
emitted++;
if (lineEnd < end) {
if (*lineEnd == '\r' && lineEnd + 1 < end && *(lineEnd + 1) == '\n')
lineEnd++;
lineEnd++;
}
p = lineEnd;
}
fflush(stdout);
ctx->preprocessedTextSize += emitted;
}
CWUnlockMemHandle(ctx, docinfo->text);
}
}
return cwNoErr;
}
/* ============================================================
* Memory Handle Management
* ============================================================ */
CW_CALLBACK CWAllocateMemory(CWPluginContext ctx, SInt32 size, Boolean isPermanent, void** ptr) {
void* p;
LOG("CWAllocateMemory(size=%d, isPermanent=%d)", (int)size, (int)isPermanent);
if (!ctx || !ptr) return cwErrInvalidParameter;
if (size < 0) return cwErrInvalidParameter;
if (size == 0) {
*ptr = NULL;
return cwNoErr;
}
p = calloc(1, (size_t)size);
if (!p) return cwErrOutOfMemory;
*ptr = p;
return cwNoErr;
}
CW_CALLBACK CWFreeMemory(CWPluginContext ctx, void* ptr, Boolean isPermanent) {
LOG("CWFreeMemory(ptr=%p, isPermanent=%d)", ptr, (int)isPermanent);
if (!ctx) return cwErrInvalidParameter;
if (ptr) free(ptr);
return cwNoErr;
}
CW_CALLBACK CWAllocMemHandle(CWPluginContext ctx,
SInt32 size, Boolean useTempMemory, CWMemHandle* handle)
{
LOG("CWAllocMemHandle(size=%d)", size);
if (!handle) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)calloc(1, sizeof(CWMemHandleImpl));
if (!h) return cwErrOutOfMemory;
if (size > 0) {
h->data = calloc(1, size);
if (!h->data) {
free(h);
return cwErrOutOfMemory;
}
}
h->size = size;
h->locked = 0;
*handle = (CWMemHandle)h;
return cwNoErr;
}
CW_CALLBACK CWFreeMemHandle(CWPluginContext ctx, CWMemHandle handle) {
LOG("CWFreeMemHandle");
if (!handle) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)handle;
if (h->data) free(h->data);
free(h);
return cwNoErr;
}
CW_CALLBACK CWGetMemHandleSize(CWPluginContext ctx,
CWMemHandle handle, SInt32* size)
{
if (!handle || !size) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)handle;
*size = h->size;
return cwNoErr;
}
CW_CALLBACK CWResizeMemHandle(CWPluginContext ctx,
CWMemHandle handle, SInt32 newSize)
{
LOG("CWResizeMemHandle(newSize=%d)", newSize);
if (!handle) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)handle;
void* newdata = realloc(h->data, newSize);
if (!newdata && newSize > 0) return cwErrOutOfMemory;
h->data = newdata;
h->size = newSize;
return cwNoErr;
}
CW_CALLBACK CWLockMemHandle(CWPluginContext ctx,
CWMemHandle handle, Boolean moveHi, void** ptr)
{
if (!handle || !ptr) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)handle;
h->locked++;
*ptr = h->data;
return cwNoErr;
}
CW_CALLBACK CWUnlockMemHandle(CWPluginContext ctx, CWMemHandle handle) {
if (!handle) return cwErrInvalidParameter;
CWMemHandleImpl* h = (CWMemHandleImpl*)handle;
if (h->locked > 0) h->locked--;
return cwNoErr;
}
/* ============================================================
* Source File Access
* ============================================================ */
CW_CALLBACK CWGetMainFileSpec(CWPluginContext ctx, CWFileSpec* fileSpec) {
LOG("CWGetMainFileSpec");
if (!ctx || !fileSpec) return cwErrInvalidParameter;
cwfilespec_from_cpath(fileSpec, ctx->sourceFile);
return cwNoErr;
}
CW_CALLBACK CWGetMainFileText(CWPluginContext ctx,
const char** text, SInt32* textLength)
{
LOG("CWGetMainFileText");
if (!ctx || !text || !textLength) return cwErrInvalidParameter;
if (!ctx->sourceText) return cwErrFileNotFound;
*text = ctx->sourceText;
*textLength = ctx->sourceTextSize;
return cwNoErr;
}
CW_CALLBACK CWGetMainFileNumber(CWPluginContext ctx, SInt32* fileNumber) {
LOG("CWGetMainFileNumber");
if (!ctx || !fileNumber) return cwErrInvalidParameter;
*fileNumber = ctx->whichFile;
return cwNoErr;
}
CW_CALLBACK CWGetMainFileID(CWPluginContext ctx, short* fileID) {
LOG("CWGetMainFileID");
if (!ctx || !fileID) return cwErrInvalidParameter;
*fileID = (short)(ctx->whichFile + 1);
return cwNoErr;
}
CW_CALLBACK CWGetFileText(CWPluginContext ctx,
const CWFileSpec* filespec, const char** text, SInt32* textLength, short* filedatatype)
{
char path[MAX_PATH];
path[0] = '\0';
if (filespec) {
cwfilespec_to_cpath(filespec, path, sizeof(path));
}
LOG("CWGetFileText(%s)", filespec ? path : "NULL");
if (!ctx || !filespec || !text || !textLength) return cwErrInvalidParameter;
SInt32 size;
char* buf = read_and_fix_file(path, &size);
if (!buf) return cwErrFileNotFound;
*text = buf;
*textLength = size;
if (filedatatype) *filedatatype = cwFileTypeText;
return cwNoErr;
}
CW_CALLBACK CWReleaseFileText(CWPluginContext ctx, const char* text) {
LOG("CWReleaseFileText");
if (text && ctx) {
/* Don't free the main source text - we own that */
if (text != ctx->sourceText) {
free((void*)text);
}
}
return cwNoErr;
}
static int is_cmdline_defines_name(const char* filename) {
const size_t name_len = strlen(CMDLINE_DEFINES_VFILE);
static const char* alt_name = "command-line defines)";
const size_t alt_len = 21;
if (!filename) return 0;
/* C-string form */
if (strncmp(filename, CMDLINE_DEFINES_VFILE, name_len) == 0 && filename[name_len] == '\0')
return 1;
if (strncmp(filename, alt_name, alt_len) == 0 && filename[alt_len] == '\0')
return 1;
/* Pascal Str31 form */
if ((unsigned char)filename[0] == name_len &&
memcmp(filename + 1, CMDLINE_DEFINES_VFILE, name_len) == 0)
return 1;
if ((unsigned char)filename[0] == alt_len &&
memcmp(filename + 1, alt_name, alt_len) == 0)
return 1;
return 0;
}
CW_CALLBACK CWFindAndLoadFile(CWPluginContext ctx,
const char* filename, CWFileInfo* fileinfo)
{
CWFileInfo* fileinfo_out;
if (!ctx || !filename || !fileinfo) return cwErrInvalidParameter;
fileinfo_out = fileinfo;
/* Keep request fields before clearing output. */
Boolean fullsearch = fileinfo_out->fullsearch;
SInt32 dependent_file = fileinfo_out->isdependentoffile;
Boolean suppressload = fileinfo_out->suppressload;
/*
* Copy filename BEFORE memset: the DLL may pass a pointer that overlaps
* with fileinfo storage.
*/
char fname[MAX_PATH];
char special_dir[MAX_PATH];
int have_special_dir = 0;
if (ctx->fileRecordCount == 0 && ctx->sourceFile[0]) {
record_file_id(ctx, (short)(ctx->whichFile + 1), ctx->sourceFile, FALSE);
}
cw_filename_arg_to_cpath(filename, fname, sizeof(fname));
LOG("CWFindAndLoadFile(%s, fullsearch=%d, dep=%d, suppress=%d)",
fname, (int)fullsearch, (int)dependent_file, (int)suppressload);
if (is_cmdline_defines_name(fname)) {
filename = CMDLINE_DEFINES_VFILE;
} else {
filename = fname;
}
memset(fileinfo_out, 0, sizeof(*fileinfo_out));
/* MWCC-style command-line virtual prefix file. */
if (ctx->defineText && ctx->defineTextLen > 0 &&
strcmp(filename, CMDLINE_DEFINES_VFILE) == 0)
{
if (!suppressload) {
char* buf = (char*)malloc((size_t)ctx->defineTextLen + 1);
if (!buf) return cwErrOutOfMemory;
memcpy(buf, ctx->defineText, (size_t)ctx->defineTextLen);
buf[ctx->defineTextLen] = '\0';
fileinfo_out->filedata = buf;
fileinfo_out->filedatalength = ctx->defineTextLen;
} else {
fileinfo_out->filedata = NULL;
fileinfo_out->filedatalength = 0;
}
fileinfo_out->filedatatype = cwFileTypeText;
fileinfo_out->fileID = 0;
cwfilespec_from_cpath(&fileinfo_out->filespec, CMDLINE_DEFINES_VFILE);
fileinfo_out->alreadyincluded = FALSE;
fileinfo_out->recordbrowseinfo = FALSE;
return cwNoErr;
}
fullsearch = (fullsearch || ctx->noSysPath) ? TRUE : FALSE;
if (is_full_path(filename)) {
if (load_file_for_include(filename, fileinfo, ctx, suppressload, FALSE) == cwNoErr) {
return cwNoErr;
}
}
switch (ctx->includeSearchMode) {
case hostIncludeSearchProj:
have_special_dir = GetCurrentDirectoryA(MAX_PATH, special_dir) > 0;
break;
case hostIncludeSearchSource:
if (ctx->sourceFile[0]) {
get_directory(ctx->sourceFile, special_dir, sizeof(special_dir));
have_special_dir = 1;
}
break;
case hostIncludeSearchInclude:
if (fullsearch && dependent_file >= 0) {
const char* dep_path = lookup_file_id_path(ctx, (short)dependent_file);
if (dep_path && dep_path[0]) {
get_directory(dep_path, special_dir, sizeof(special_dir));
have_special_dir = 1;
}
}
if (fullsearch && !have_special_dir && ctx->lastIncludeDir[0]) {
copy_cstr(special_dir, sizeof(special_dir), ctx->lastIncludeDir);
have_special_dir = 1;
}
if (!have_special_dir && ctx->sourceFile[0]) {
get_directory(ctx->sourceFile, special_dir, sizeof(special_dir));
have_special_dir = 1;
}
break;
case hostIncludeSearchExplicit:
default:
break;
}
if (have_special_dir &&
try_load_include(special_dir, filename, fileinfo, ctx, suppressload, FALSE, FALSE) == cwNoErr)
{
return cwNoErr;
}
if (fullsearch) {
for (SInt32 i = 0; i < ctx->userPathCount; i++) {
if (try_load_include(ctx->userPaths[i].path, filename, fileinfo,
ctx, suppressload, ctx->userPaths[i].recursive, FALSE) == cwNoErr)
return cwNoErr;
}
}
for (SInt32 i = 0; i < ctx->systemPathCount; i++) {
if (try_load_include(ctx->systemPaths[i].path, filename, fileinfo,
ctx, suppressload, ctx->systemPaths[i].recursive, TRUE) == cwNoErr)
return cwNoErr;
}
fprintf(stderr, "Cannot find include file: %s\n", filename);
return cwErrFileNotFound;
}
/* ============================================================
* Object Data Storage
* ============================================================ */
CW_CALLBACK CWStoreObjectData(CWPluginContext ctx,
SInt32 whichfile, CWObjectData* object)
{
LOG("CWStoreObjectData(whichfile=%d, codesize=%d, udatasize=%d, idatasize=%d)",
whichfile, object ? object->codesize : 0,
object ? object->udatasize : 0, object ? object->idatasize : 0);
if (!ctx || !object) return cwErrInvalidParameter;
ctx->storedObject = *object;
ctx->objectStored = 1;
/* Copy the object data to our own buffer */
if (object->objectdata) {
void* ptr = NULL;
SInt32 size = 0;
CWGetMemHandleSize(ctx, object->objectdata, &size);
CWLockMemHandle(ctx, object->objectdata, FALSE, &ptr);
LOG(" objectdata: ptr=%p, size=%d", ptr, size);
if (ptr && size > 0) {
ctx->objectData = malloc(size);
if (ctx->objectData) {
memcpy(ctx->objectData, ptr, size);
ctx->objectDataSize = size;
LOG(" Captured %d bytes of object data", size);
}
} else if (ptr) {
/* Size unknown (from CWSecretAttachHandle), use codesize+udatasize+idatasize */
SInt32 totalSize = object->codesize + object->udatasize + object->idatasize;
if (totalSize <= 0) totalSize = 4096; /* fallback guess */
LOG(" Using computed size: %d", totalSize);
ctx->objectData = malloc(totalSize);
if (ctx->objectData) {
memcpy(ctx->objectData, ptr, totalSize);
ctx->objectDataSize = totalSize;
LOG(" Captured %d bytes of object data (computed)", totalSize);
}
}
CWUnlockMemHandle(ctx, object->objectdata);
}
return cwNoErr;
}
CW_CALLBACK CWLoadObjectData(CWPluginContext ctx,
SInt32 whichfile, CWMemHandle* objectdata)
{
LOG("CWLoadObjectData(whichfile=%d)", whichfile);
if (!ctx || !objectdata) return cwErrInvalidParameter;
if (!ctx->objectData || ctx->objectDataSize <= 0) {
return cwErrObjectFileNotStored;
}
CWMemHandle h = NULL;
CWResult r = CWAllocMemHandle(ctx, ctx->objectDataSize, FALSE, &h);
if (r != cwNoErr) return r;