winemaker 92.3 KB
Newer Older
1
#!/usr/bin/perl -w
2
use strict;
3

4
# Copyright 2000-2004 Francois Gouget for CodeWeavers
5
# Copyright 2004 Dimitrie O. Paun
6
# Copyright 2009-2012 André Hentschel
7
#
8 9 10 11 12 13 14 15 16 17 18 19
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
20
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 22
#

23
my $version="0.8.3";
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

use Cwd;
use File::Basename;
use File::Copy;



#####
#
# Options
#
#####

# The following constants define what we do with the case of filenames

##
# Never rename a file to lowercase
my $OPT_LOWER_NONE=0;

##
# Rename all files to lowercase
my $OPT_LOWER_ALL=1;

##
# Rename only files that are all uppercase to lowercase
my $OPT_LOWER_UPPERCASE=2;


# The following constants define whether to ask questions or not

##
# No (synonym of never)
my $OPT_ASK_NO=0;

##
# Yes (always)
my $OPT_ASK_YES=1;

##
# Skip the questions till the end of this scope
my $OPT_ASK_SKIP=-1;


67 68
# The following constants define the architecture

69
##
70
# Default Architecture will be chosen
71 72
my $OPT_ARCH_DEFAULT=0;

73 74 75 76 77 78 79 80 81
##
# 32-Bit Target
my $OPT_ARCH_32=32;

##
# 64-Bit Target
my $OPT_ARCH_64=64;


82 83
# General options

84 85 86 87
##
# This is the directory in which winemaker will operate.
my $opt_work_dir;

88 89 90 91
##
# This is the file in which winemaker will operate if a project file is specified.
my $opt_work_file;

92 93 94 95 96 97 98 99
##
# Make a backup of the files
my $opt_backup;

##
# Defines which files to rename
my $opt_lower;

100 101 102 103
##
# If we don't find the file referenced by an include, lower it
my $opt_lower_include;

104 105 106 107 108
##
# If true then winemaker should not attempt to fix the source.  This is
# useful if the source is known to be already in a suitable form and is
# readonly
my $opt_no_source_fix;
109 110 111 112

# Options for the 'Source' method

##
113 114 115 116
# Specifies that we have only one target so that all sources relate
# to this target. By default this variable is left undefined which
# means winemaker should try to find out by itself what the targets
# are. If not undefined then this contains the name of the default
117 118 119 120
# target (without the extension).
my $opt_single_target;

##
121 122
# If '$opt_single_target' has been specified then this is the type of
# that target. Otherwise it specifies whether the default target type
123 124 125 126 127 128 129
# is guiexe or cuiexe.
my $opt_target_type;

##
# Contains the default set of flags to be used when creating a new target.
my $opt_flags;

130 131 132 133
##
# Contains 32 for 32-Bit-Targets and 64 for 64-Bit-Targets
my $opt_arch;

134
##
135
# If true then winemaker should ask questions to the user as it goes
136 137 138 139 140 141
# along.
my $opt_is_interactive;
my $opt_ask_project_options;
my $opt_ask_target_options;

##
142
# If false then winemaker should not generate the makefiles.
143
my $opt_no_generated_files;
144 145 146 147 148 149 150 151 152 153 154 155 156

##
# Specifies not to print the banner if set.
my $opt_no_banner;



#####
#
# Target modelization
#
#####

157
# The description of a target is stored in an array. The constants
158 159 160 161 162 163 164 165 166 167 168 169
# below identify what is stored at each index of the array.

##
# This is the name of the target.
my $T_NAME=0;

##
# Defines the type of target we want to build. See the TT_xxx
# constants below
my $T_TYPE=1;

##
170
# This is a bitfield containing flags refining the way the target
171
# should be handled. See the TF_xxx constants below
172
my $T_FLAGS=2;
173 174

##
175
# This is a reference to an array containing the list of the
176
# resp. C, C++, RC, other (.h, .hxx, etc.) source files.
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
my $T_SOURCES_C=3;
my $T_SOURCES_CXX=4;
my $T_SOURCES_RC=5;
my $T_SOURCES_MISC=6;

##
# This is a reference to an array containing the list of
# C compiler options
my $T_CEXTRA=7;

##
# This is a reference to an array containing the list of
# C++ compiler options
my $T_CXXEXTRA=8;

##
# This is a reference to an array containing the list of
# RC compiler options
my $T_RCEXTRA=9;
196 197

##
198
# This is a reference to an array containing the list of macro
199
# definitions
200
my $T_DEFINES=10;
201 202

##
203
# This is a reference to an array containing the list of directory
204
# names that constitute the include path
205 206 207 208 209
my $T_INCLUDE_PATH=11;

##
# Flags for the linker
my $T_LDFLAGS=12;
210

211 212 213 214
##
# Flags for the archiver
my $T_ARFLAGS=13;

215
##
216
# Same as T_INCLUDE_PATH but for the dll search path
217
my $T_DLL_PATH=14;
218 219 220

##
# The list of Windows dlls to import
221
my $T_DLLS=15;
222 223

##
224
# Same as T_INCLUDE_PATH but for the library search path
225
my $T_LIBRARY_PATH=16;
226 227 228

##
# The list of Unix libraries to link with
229
my $T_LIBRARIES=17;
230 231 232 233 234


# The following constants define the recognized types of target

##
235
# This is not a real target. This type of target is used to collect
236
# the sources that don't seem to belong to any other target. Thus no
237
# real target is generated for them, we just put the sources of the
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
# fake target in the global source list.
my $TT_SETTINGS=0;

##
# For executables in the windows subsystem
my $TT_GUIEXE=1;

##
# For executables in the console subsystem
my $TT_CUIEXE=2;

##
# For dynamically linked libraries
my $TT_DLL=3;

253 254 255 256
##
# For static libraries
my $TT_LIB=4;

257 258 259 260 261 262 263

# The following constants further refine how the target should be handled

##
# This target is an MFC-based target
my $TF_MFC=4;

264 265 266 267 268 269 270 271
##
# User has specified --nomfc option for this target or globally
my $TF_NOMFC=8;

##
# --nodlls option: Do not use standard DLL set
my $TF_NODLLS=16;

272 273 274 275
##
# --nomsvcrt option: Do not link with msvcrt
my $TF_NOMSVCRT=32;

276 277 278 279
##
# This target has a def file (only use it with TT_DLL)
my $TF_HASDEF=64;

280 281 282 283
##
# This target has C++ files named *.cxx (instead of *.cpp)
my $TF_HASCXX=128;

284 285
##
# Initialize a target:
286 287
# - set the target type to TT_SETTINGS, i.e. no real target will
#   be generated.
288
sub target_init($)
289 290 291 292 293 294 295 296 297
{
  my $target=$_[0];

  @$target[$T_TYPE]=$TT_SETTINGS;
  @$target[$T_FLAGS]=$opt_flags;
  @$target[$T_SOURCES_C]=[];
  @$target[$T_SOURCES_CXX]=[];
  @$target[$T_SOURCES_RC]=[];
  @$target[$T_SOURCES_MISC]=[];
298 299 300
  @$target[$T_CEXTRA]=[];
  @$target[$T_CXXEXTRA]=[];
  @$target[$T_RCEXTRA]=[];
301 302
  @$target[$T_DEFINES]=[];
  @$target[$T_INCLUDE_PATH]=[];
303
  @$target[$T_LDFLAGS]=[];
304
  @$target[$T_ARFLAGS]=[];
305 306
  @$target[$T_DLL_PATH]=[];
  @$target[$T_DLLS]=[];
307
  @$target[$T_LIBRARY_PATH]=[];
308
  @$target[$T_LIBRARIES]=[];
309 310 311 312 313 314 315 316 317 318
}



#####
#
# Project modelization
#
#####

319 320
# First we have the notion of project. A project is described by an
# array (since we don't have structs in perl). The constants below
321 322 323
# identify what is stored at each index of the array.

##
324
# This is the path in which this project is located. In other
325
# words, this is the path to the Makefile.
326 327 328
my $P_PATH=0;

##
329 330
# This index contains a reference to an array containing the project-wide
# settings. The structure of that arrray is actually identical to that of
331 332 333 334
# a regular target since it can also contain extra sources.
my $P_SETTINGS=1;

##
335 336 337
# This index contains a reference to an array of targets for this
# project. Each target describes how an executable or library is to
# be built. For each target this description takes the same form as
338 339 340 341 342 343 344 345
# that of the project: an array. So this entry is an array of arrays.
my $P_TARGETS=2;

##
# Initialize a project:
# - set the project's path
# - initialize the target list
# - create a default target (will be removed later if unnecessary)
346
sub project_init($$$)
347
{
348
  my ($project, $path, $global_settings)=@_;
349 350 351

  my $project_settings=[];
  target_init($project_settings);
352 353 354 355 356 357
  @$project_settings[$T_DEFINES]=[@{@$global_settings[$T_DEFINES]}];
  @$project_settings[$T_INCLUDE_PATH]=[@{@$global_settings[$T_INCLUDE_PATH]}];
  @$project_settings[$T_DLL_PATH]=[@{@$global_settings[$T_DLL_PATH]}];
  @$project_settings[$T_DLLS]=[@{@$global_settings[$T_DLLS]}];
  @$project_settings[$T_LIBRARY_PATH]=[@{@$global_settings[$T_LIBRARY_PATH]}];
  @$project_settings[$T_LIBRARIES]=[@{@$global_settings[$T_LIBRARIES]}];
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

  @$project[$P_PATH]=$path;
  @$project[$P_SETTINGS]=$project_settings;
  @$project[$P_TARGETS]=[];
}



#####
#
# Global variables
#
#####

my %warnings;

my %templates;

376 377 378 379 380
##
# This maps a directory name to a reference to an array listing
# its contents (files and directories)
my %directories;

381
##
382 383
# Contains the list of all projects. This list tells us what are
# the subprojects of the main Makefile and where we have to generate
384 385 386 387
# Makefiles.
my @projects=();

##
388 389
# This is the main project, i.e. the one in the "." directory.
# It may well be empty in which case the main Makefile will only
390 391 392 393 394
# call out subprojects.
my @main_project;

##
# Contains the defaults for the include path, etc.
395
# We store the defaults as if this were a target except that we only
396 397 398 399 400 401 402 403 404 405 406 407 408
# exploit the defines, include path, library path, library list and misc
# sources fields.
my @global_settings;



#####
#
# Utility functions
#
#####

##
409
# Cleans up a name to make it an acceptable Makefile
410
# variable name.
411
sub canonize($)
412 413 414 415 416 417 418 419 420
{
  my $name=$_[0];

  $name =~ tr/a-zA-Z0-9_/_/c;
  return $name;
}

##
# Returns true is the specified pathname is absolute.
421
# Note: pathnames that start with a variable '$' or
422
# '~' are considered absolute.
423
sub is_absolute($)
424 425 426 427 428 429
{
  my $path=$_[0];

  return ($path =~ /^[\/~\$]/);
}

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
##
# Retrieves the contents of the specified directory.
# We either get it from the directories hashtable which acts as a
# cache, or use opendir, readdir, closedir and store the result
# in the hashtable.
sub get_directory_contents($)
{
  my $dirname=$_[0];
  my $directory;

  #print "getting the contents of $dirname\n";

  # check for a cached version
  $dirname =~ s+/$++;
  if ($dirname eq "") {
    $dirname=cwd;
  }
  $directory=$directories{$dirname};
  if (defined $directory) {
    #print "->@$directory\n";
    return $directory;
  }

  # Read this directory
  if (opendir(DIRECTORY, "$dirname")) {
    my @files=readdir DIRECTORY;
    closedir(DIRECTORY);
    $directory=\@files;
  } else {
    # Return an empty list
    #print "error: cannot open $dirname\n";
    my @files;
    $directory=\@files;
  }
  #print "->@$directory\n";
  $directories{$dirname}=$directory;
  return $directory;
}

469 470 471 472 473 474 475 476
##
# Removes a directory from the cache.
# This is needed if one of its files or subdirectory has been renamed.
sub clear_directory_cache($)
{
    my ($dirname)=@_;
    delete $directories{$dirname};
}
477 478 479 480 481 482 483 484 485 486 487 488


#####
#
# 'Source'-based Project analysis
#
#####

##
# Allows the user to specify makefile and target specific options
# - target: the structure in which to store the results
# - options: the string containing the options
489
sub source_set_options($$)
490 491 492 493 494
{
  my $target=$_[0];
  my $options=$_[1];

  #FIXME: we must deal with escaping of stuff and all
495
  foreach my $option (split / /,$options) {
496 497 498 499
    if (@$target[$T_TYPE] == $TT_SETTINGS and $option =~ /^-D/) {
      push @{@$target[$T_DEFINES]},$option;
    } elsif (@$target[$T_TYPE] == $TT_SETTINGS and $option =~ /^-I/) {
      push @{@$target[$T_INCLUDE_PATH]},$option;
500 501 502
    } elsif ($option =~ /^-P/) {
      push @{@$target[$T_DLL_PATH]},"-L$'";
    } elsif ($option =~ /^-i/) {
503
      push @{@$target[$T_DLLS]},"$'";
504 505
    } elsif ($option =~ /^-L/) {
      push @{@$target[$T_LIBRARY_PATH]},$option;
506
    } elsif ($option =~ /^-l/) {
507
      push @{@$target[$T_LIBRARIES]},"$'";
508 509 510
    } elsif ($option =~ /^--mfc/) {
      @$target[$T_FLAGS]|=$TF_MFC;
      @$target[$T_FLAGS]&=~$TF_NOMFC;
511 512
    } elsif ($option =~ /^--nomfc/) {
      @$target[$T_FLAGS]&=~$TF_MFC;
513 514 515
      @$target[$T_FLAGS]|=$TF_NOMFC;
    } elsif ($option =~ /^--nodlls/) {
      @$target[$T_FLAGS]|=$TF_NODLLS;
516 517
    } elsif ($option =~ /^--nomsvcrt/) {
      @$target[$T_FLAGS]|=$TF_NOMSVCRT;
518
    } else {
519 520
      print STDERR "error: unknown option \"$option\"\n";
      return 0;
521 522
    }
  }
523
  return 1;
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
##
# Scans the specified project file to:
# - get a list of targets for this project
# - get some settings
# - get the list of source files
sub source_scan_project_file($$$);
sub source_scan_project_file($$$)
{
    # a reference to the parent's project
    my $parent_project=$_[0];
    # 0 if it is a single project, 1 if it is part of a workspace
    my $is_sub_project=$_[1];
    # the name of the project file, with complete path, or without if in
    # the same directory
    my $filename=$_[2];

    # reference to the project for this file. May not be used
    my $project;
    # list of sources found in the current file
    my @sources_c=();
    my @sources_cxx=();
    my @sources_rc=();
    my @sources_misc=();
    # some more settings
    my $path=dirname($filename);
    my $prj_target_cflags;
552
    my $prj_target_defines;
553 554 555 556 557
    my $prj_target_ldflags;
    my $prj_target_libs;
    my $prj_name;
    my $found_cfg=0;
    my $prj_cfg;
558
    my $prj_target_type=$TT_GUIEXE;
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
    my @prj_target_options;

    if (!($path=~/\/$/)) {
        $path.="/";
    }

    if (defined $opt_single_target or $is_sub_project == 0) {
        # Either there is a single target and thus a single project,
        # or we are a single project-file for which a project
        # already exists
        $project=$parent_project;
    } else {
        $project=[];
        project_init($project, $path, \@global_settings);
    }
    my $project_settings=@$project[$P_SETTINGS];

    if ($filename =~ /.dsp$/i) {
        # First find out what this project file contains:
        # collect all sources, find targets and settings
        if (!open(FILEI,$filename)) {
            print STDERR "error: unable to open $filename for reading:\n";
            print STDERR "       $!\n";
            return;
        }
        my $sfilet;
        while (<FILEI>) {
            # Remove any trailing CtrlZ, which isn't strictly in the file
            if (/\x1A/) {
                s/\x1A//;
                last if (/^$/)
            }

            # Remove any trailing CrLf
            s/\r\n$/\n/;
            if (!/\n$/) {
                # Make sure all lines are '\n' terminated
                $_ .= "\n";
            }

            if (/^\# Microsoft Developer Studio Project File - Name=\"([^\"]+)/) {
600
                $prj_name="$1";
601
                $prj_name=~s/\s+/_/g;
602 603 604
                #print $prj_name;
                next;
            } elsif (/^# TARGTYPE/) {
605
                if (/[[:space:]]0+x0*101$/) {
606 607
                    # Application
                    $prj_target_type=$TT_GUIEXE;
608
                }elsif (/[[:space:]]0+x0*102$/) {
609 610
                    # Dynamic-Link Library
                    $prj_target_type=$TT_DLL;
611
                }elsif (/[[:space:]]0+x0*103$/) {
612 613
                    # Console Application
                    $prj_target_type=$TT_CUIEXE;
614
                }elsif (/[[:space:]]0+x0*104$/) {
615
                    # Static Library
616
                    $prj_target_type=$TT_LIB;
617 618 619 620
                }
                next;
            } elsif (/^# ADD CPP(.*)/ && $found_cfg==1) {
                $prj_target_cflags=$1;
621
                @prj_target_options=split(/\s+\//, $prj_target_cflags);
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
                $prj_target_cflags="";
                foreach ( @prj_target_options ) {
                    if ($_ eq "") {
                        # empty
                    } elsif (/nologo/) {
                        # Suppress Startup Banner and Information Messages
                    } elsif (/^W0$/) {
                        # Turns off all warning messages
                        $prj_target_cflags.="-w ";
                    } elsif (/^W[123]$/) {
                        # Warning Level
                        $prj_target_cflags.="-W ";
                    } elsif (/^W4$/) {
                        # Warning Level
                        $prj_target_cflags.="-Wall ";
                    } elsif (/^WX$/) {
                        # Warnings As Errors
                        $prj_target_cflags.="-Werror ";
                    } elsif (/^Gm$/) {
                        # Enable Minimal Rebuild
                    } elsif (/^GX$/) {
                        # Enable Exception Handling
                        $prj_target_cflags.="-fexceptions ";
645 646 647 648 649 650 651
                    } elsif (/^Gd$/) {
                        # use cdecl calling convention (default)
                    } elsif (/^Gr$/) {
                        # use fastcall calling convention
                    } elsif (/^Gz$/) {
                        # use stdcall calling convention
                        $prj_target_cflags.="-mrtd ";
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
                    } elsif (/^Z[d7iI]$/) {
                        # Debug Info
                        $prj_target_cflags.="-g ";
                    } elsif (/^Od$/) {
                        # Disable Optimizations
                        $prj_target_cflags.="-O0 ";
                    } elsif (/^O1$/) {
                        # Minimize Size
                        $prj_target_cflags.="-Os ";
                    } elsif (/^O2$/) {
                        # Maximize Speed
                        $prj_target_cflags.="-O2 ";
                    } elsif (/^Ob0$/) {
                        # Disables inline Expansion
                        $prj_target_cflags.="-fno-inline ";
                    } elsif (/^Ob1$/) {
668 669
                        #In-line Function Expansion
                        $prj_target_cflags.="-finline-functions ";
670 671 672
                    } elsif (/^Ob2$/) {
                        # auto In-line Function Expansion
                        $prj_target_cflags.="-finline-functions ";
673 674 675
                    } elsif (/^Ox$/) {
                        # Use maximum optimization
                        $prj_target_cflags.="-O3 ";
676 677 678
                    } elsif (/^Oy$/) {
                        # Frame-Pointer Omission
                        $prj_target_cflags.="-fomit-frame-pointer ";
679 680 681
                    } elsif (/^Oy-$/) {
                        # Frame-Pointer Omission
                        $prj_target_cflags.="-fno-omit-frame-pointer ";
682 683 684 685 686 687
                    } elsif (/^GZ$/) {
                        # Catch Release-Build Errors in Debug Build
                    } elsif (/^M[DLT]d?$/) {
                        # Use Multithreaded Run-Time Library
                    } elsif (/^D\s*\"(.*)\"/) {
                        # Preprocessor Definitions
688
                        $prj_target_defines.="-D".$1." ";
689
                    } elsif (/^I\s*\"(.*)\"/) {
690
                        # Additional Include Directories
691 692
                        $sfilet=$1;
                        $sfilet=~s/\\/\//g;
693 694 695 696 697
                        if ($sfilet=~/^\w:/) {
                            print STDERR "warning: Can't fix path $sfilet\n"
                        } else {
                            push @{@$project_settings[$T_INCLUDE_PATH]},"-I".$sfilet." ";
                        }
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
                    } elsif (/^U\s*\"(.*)\"/) {
                        # Undefines a previously defined symbol
                        $prj_target_cflags.="-U".$1." ";
                    } elsif (/^Fp/) {
                        # Name .PCH File
                    } elsif (/^F[Rr]/) {
                        # Create .SBR File
                    } elsif (/^YX$/) {
                        # Automatic Use of Precompiled Headers
                    } elsif (/^FD$/) {
                        # Generate File Dependencies
                    } elsif (/^c$/) {
                        # Compile Without Linking
                        # this option is always present and is already specified in the suffix rules
                    } elsif (/^GB$/) {
                        # Blend Optimization
714
                        $prj_target_cflags.="-D_M_IX86=500 ";
715 716
                    } elsif (/^G6$/) {
                        # Pentium Pro Optimization
717
                        $prj_target_cflags.="-D_M_IX86=600 ";
718 719
                    } elsif (/^G5$/) {
                        # Pentium Optimization
720
                        $prj_target_cflags.="-D_M_IX86=500 ";
721 722
                    } elsif (/^G3$/) {
                        # 80386 Optimization
723
                        $prj_target_cflags.="-D_M_IX86=300 ";
724 725
                    } elsif (/^G4$/) {
                        # 80486 Optimization
726
                        $prj_target_cflags.="-D_M_IX86=400 ";
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
                    } elsif (/^Yc/) {
                        # Create Precompiled Header
                    } elsif (/^Yu/) {
                        # Use Precompiled Header
                    } elsif (/^Za$/) {
                        # Disable Language Extensions
                        $prj_target_cflags.="-ansi ";
                    } elsif (/^Ze$/) {
                        # Enable Microsoft Extensions
                    } elsif (/^Zm[[:digit:]]+$/) {
                        # Specify Memory Allocation Limit
                    } elsif (/^Zp1?$/) {
                        # Packs structures on 1-byte boundaries
                        $prj_target_cflags.="-fpack-struct ";
                    } elsif (/^Zp(2|4|8|16)$/) {
                        # Struct Member Alignment
                        $prj_target_cflags.="-fpack-struct=".$1;
                    } else {
                        print "C compiler option $_ not implemented\n";
                    }
                }

                #print "\nOptions: $prj_target_cflags\n";
                next;
            } elsif (/^# ADD LINK32(.*)/ && $found_cfg==1) {
                $prj_target_ldflags=$1;
753
                @prj_target_options=split(/\s+\//, $prj_target_ldflags);
754 755 756 757
                $prj_target_ldflags="";
                $prj_target_libs=$prj_target_options[0];
                $prj_target_libs=~s/\\/\//g;
                $prj_target_libs=~s/\.lib//g;
758
                $prj_target_libs=~s/\s+/ -l/g;
759 760 761 762 763 764 765 766 767 768 769
                shift (@prj_target_options);
                foreach ( @prj_target_options ) {
                    if ($_ eq "") {
                        # empty
                    } elsif (/^base:(.*)/) {
                        # Base Address
                        $prj_target_ldflags.="--image-base ".$1." ";
                    } elsif (/^debug$/) {
                        # Generate Debug Info
                    } elsif (/^dll$/) {
                        # Build a DLL
770
                        $prj_target_type=$TT_DLL;
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
                    } elsif (/^incremental:[[:alpha:]]+$/) {
                        # Link Incrmentally
                    } elsif (/^implib:/) {
                        # Name import library
                    } elsif (/^libpath:\"(.*)\"/) {
                        # Additional Libpath
                        push @{@$project_settings[$T_DLL_PATH]},"-L$1";
                    } elsif (/^machine:[[:alnum:]]+$/) {
                        # Specify Target Platform
                    } elsif (/^map/) {
                        # Generate Mapfile
                        if (/^map:(.*)/) {
                            $prj_target_ldflags.="-Map ".$1." ";
                        } else {
                            $prj_target_ldflags.="-Map ".$prj_name.".map ";
                        }
                    } elsif (/^nologo$/) {
                        # Suppress Startup Banner and Information Messages
                    } elsif (/^out:/) {
                        # Output File Name
                        # may use it as Target?
                    } elsif (/^pdbtype:/) {
                        # Program Database Storage
                    } elsif (/^subsystem:/) {
                        # Specify Subsystem
                    } elsif (/^version:[[:digit:].]+$/) {
                        # Version Information
                    } else {
                        print "Linker option $_ not implemented\n";
                    }
                }
                next;
            } elsif (/^LIB32=/ && $found_cfg==1) {
                #$libflag = 1;
                next;
            } elsif (/^SOURCE=(.*)$/) {
                my @components=split /[\/\\]+/, $1;
                $sfilet=search_from($path, \@components);
809
                if (!defined $sfilet) { next; }
810
                if ($sfilet =~ /\.c$/i and $sfilet !~ /\.(dbg|spec)\.c$/) {
811
                    push @sources_c,$sfilet;
812
                } elsif ($sfilet =~ /\.cpp$/i) {
813 814 815 816 817 818
                    if ($sfilet =~ /^stdafx.cpp$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
                        push @sources_misc,$sfilet;
                        @$project_settings[$T_FLAGS]|=$TF_MFC;
                    } else {
                        push @sources_cxx,$sfilet;
                    }
819 820 821
                } elsif ($sfilet =~ /\.cxx$/i) {
                    @$project_settings[$T_FLAGS]|=$TF_HASCXX;
                    push @sources_cxx,$sfilet;
822 823
                } elsif ($sfilet =~ /\.rc$/i) {
                    push @sources_rc,$sfilet;
824 825
                } elsif ($sfilet =~ /\.def$/i) {
                        @$project_settings[$T_FLAGS]|=$TF_HASDEF;
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
                } elsif ($sfilet =~ /\.(h|hxx|hpp|inl|rc2|dlg)$/i) {
                    push @sources_misc,$sfilet;
                    if ($sfilet =~ /^stdafx.h$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
                        @$project_settings[$T_FLAGS]|=$TF_MFC;
                    }
                }
                next;

            } elsif (/^# (Begin|End) Source File/) {
                # Source-Files already handled
                next;
            } elsif (/^# (Begin|End) Group/) {
                # Groups are ignored
                next;
            } elsif (/^# (Begin|End) Custom Build/) {
                # Custom Builds are ignored
                next;
            } elsif (/^# ADD LIB32 /) {
                #"ARFLAGS=rus"
                next;
            } elsif (/^# Begin Target$/) {
                # Targets are ignored
                next;
            } elsif (/^# End Target$/) {
                # Targets are ignored
                next;
            } elsif (/^!/) {
                if ($found_cfg == 1) {
                    $found_cfg=0;
                }
                if (/if (.*)\(CFG\)" == "(.*)"/i) {
                    if ($2 eq $prj_cfg) {
                        $found_cfg=1;
                    }
                }
                next;
            } elsif (/^CFG=(.*)/i) {
                $prj_cfg=$1;
                next;
            }
                else { # Line recognized
                # print "|\n";
            }
        }
        close(FILEI);

        push @{@$project_settings[$T_LIBRARIES]},$prj_target_libs;
        push @{@$project_settings[$T_CEXTRA]},$prj_target_cflags;
        push @{@$project_settings[$T_CXXEXTRA]},$prj_target_cflags;
875
        push @{@$project_settings[$T_DEFINES]},$prj_target_defines;
876 877
        push @{@$project_settings[$T_LDFLAGS]},$prj_target_ldflags;
    } elsif ($filename =~ /.vcproj$/i) {
878 879
        # Import XML::LibXML, you need the libxml package (deb: libxml-libxml-perl, rpm: perl-libxml-perl)
        require XML::LibXML;
880

881 882
        my $xmlparser = XML::LibXML->new();
        my $project_xml = $xmlparser->parse_file($filename);
883
        my $sfilet;
884 885 886 887 888
        my $configt;

        foreach my $vc_project ($project_xml->findnodes('/VisualStudioProject')) {
            foreach my $vc_project_attr ($vc_project->attributes) {
                if ($vc_project_attr->getName eq "Name") {
889
                    $prj_name=$vc_project_attr->getValue;
890
                    $prj_name=~s/\s+/_/g;
891 892 893 894 895 896 897 898 899 900 901 902 903
                    last;
                }
            }
        }

        for (my $flevel = 0; $flevel <= 5; $flevel++) {
            foreach my $vc_file ($project_xml->findnodes('/VisualStudioProject/Files/'.('Filter/' x $flevel).'File')) {
                foreach my $vc_file_attr ($vc_file->attributes) {
                    if ($vc_file_attr->getName eq "RelativePath") {
                        $sfilet = $vc_file_attr->getValue;
                        $sfilet=~s/\\\\/\\/g; #remove double backslash
                        $sfilet=~s/^\.\\//; #remove starting 'this directory'
                        $sfilet=~s/\\/\//g; #make slashes out of backslashes
904
                        if ($sfilet =~ /\.c$/i and $sfilet !~ /\.(dbg|spec)\.c$/) {
905
                            push @sources_c,$sfilet;
906
                        } elsif ($sfilet =~ /\.cpp$/i) {
907 908 909 910 911 912
                            if ($sfilet =~ /^stdafx.cpp$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
                                push @sources_misc,$sfilet;
                                @$project_settings[$T_FLAGS]|=$TF_MFC;
                            } else {
                                push @sources_cxx,$sfilet;
                            }
913 914 915
                        } elsif ($sfilet =~ /\.cxx$/i) {
                            @$project_settings[$T_FLAGS]|=$TF_HASCXX;
                            push @sources_cxx,$sfilet;
916 917
                        } elsif ($sfilet =~ /\.rc$/i) {
                            push @sources_rc,$sfilet;
918 919
                        } elsif ($sfilet =~ /\.def$/i) {
                            @$project_settings[$T_FLAGS]|=$TF_HASDEF;
920
                        } elsif ($sfilet =~ /\.(h|hxx|hpp|inl|rc2|dlg)$/i) {
921
                            push @sources_misc,$sfilet;
922 923 924
                            if ($sfilet =~ /^stdafx.h$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
                                @$project_settings[$T_FLAGS]|=$TF_MFC;
                            }
925 926 927 928 929
                        }
                    }
                }
            }
        }
930 931 932 933 934 935

        my @vc_configurations = $project_xml->findnodes('/VisualStudioProject/Configurations/Configuration');
        my $vc_configuration = $vc_configurations[0];
        foreach my $vc_configuration_attr ($vc_configuration->attributes) {
            if ($vc_configuration_attr->getName eq "ConfigurationType") {
                if ($vc_configuration_attr->getValue==1) {
936
                    $prj_target_type=$TT_GUIEXE; # Application
937
                } elsif ($vc_configuration_attr->getValue==2) {
938
                    $prj_target_type=$TT_DLL; # Dynamic-Link Library
939 940
                } elsif ($vc_configuration_attr->getValue==4) {
                    $prj_target_type=$TT_LIB; # Static Library
941 942 943 944 945 946
                }
            }
        }

        foreach my $vc_configuration_tools ($vc_configuration->findnodes('Tool')) {
            my @find_tool = $vc_configuration_tools->attributes;
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
            if ($find_tool[0]->getValue eq "VCCLCompilerTool") {
                foreach my $vc_compiler_tool ($vc_configuration_tools->attributes) {
                    if ($vc_compiler_tool->getName eq "Optimization") {$prj_target_cflags.="-O".$vc_compiler_tool->getValue." ";}
                    if ($vc_compiler_tool->getName eq "WarningLevel") {
                        if ($vc_compiler_tool->getValue==0) {
                            $prj_target_cflags.="-w ";
                        } elsif ($vc_compiler_tool->getValue<4) {
                            $prj_target_cflags.="-W ";
                        } elsif ($vc_compiler_tool->getValue==4) {
                            $prj_target_cflags.="-Wall ";
                        } elsif ($vc_compiler_tool->getValue eq "X") {
                            $prj_target_cflags.="-Werror ";
                        }
                    }
                    if ($vc_compiler_tool->getName eq "PreprocessorDefinitions") {
                        $configt=$vc_compiler_tool->getValue;
963
                        $configt=~s/;\s*/ -D/g;
964
                        $prj_target_defines.="-D".$configt." ";
965 966 967 968 969 970
                    }
                    if ($vc_compiler_tool->getName eq "AdditionalIncludeDirectories") {
                        $configt=$vc_compiler_tool->getValue;
                        $configt=~s/\\/\//g;
                        $configt=~s/;/ -I/g;
                        push @{@$project_settings[$T_INCLUDE_PATH]},"-I".$configt;
971
                    }
972
                }
973 974 975 976 977 978 979 980 981
            }
            if ($find_tool[0]->getValue eq "VCLinkerTool") {
                foreach my $vc_linker_tool ($vc_configuration_tools->attributes) {
                    if ($vc_linker_tool->getName eq "AdditionalDependencies") {
                        $prj_target_libs=" ".$vc_linker_tool->getValue;
                        $prj_target_libs=~s/\\/\//g;
                        $prj_target_libs=~s/\.lib//g;
                        $prj_target_libs=~s/\s+/ -l/g;
                    }
982
                }
983 984
            }
        }
985

986
        push @{@$project_settings[$T_LIBRARIES]},$prj_target_libs;
987 988
        push @{@$project_settings[$T_CEXTRA]},$prj_target_cflags;
        push @{@$project_settings[$T_CXXEXTRA]},$prj_target_cflags;
989
        push @{@$project_settings[$T_DEFINES]},$prj_target_defines;
990 991 992
    } else {
        print STDERR "File format not supported for file: $filename\n";
        return;
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    }

    # Add this project to the project list, except for
    # the main project which is already in the list.
    if ($is_sub_project == 1) {
        push @projects,$project;
    }

    # Ask for project-wide options
    if ($opt_ask_project_options == $OPT_ASK_YES) {
        my $flag_desc="";
        if ((@$project_settings[$T_FLAGS] & $TF_MFC)!=0) {
            $flag_desc="mfc";
        }
        print "* Type any project-wide options (-D/-I/-P/-i/-L/-l/--mfc),\n";
        if (defined $flag_desc) {
            print "* (currently $flag_desc)\n";
        }
        print "* or 'skip' to skip the target specific options,\n";
        print "* or 'never' to not be asked this question again:\n";
        while (1) {
            my $options=<STDIN>;
            chomp $options;
            if ($options eq "skip") {
                $opt_ask_target_options=$OPT_ASK_SKIP;
                last;
            } elsif ($options eq "never") {
                $opt_ask_project_options=$OPT_ASK_NO;
                last;
            } elsif (source_set_options($project_settings,$options)) {
                last;
            }
            print "Please re-enter the options:\n";
        }
    }

1029 1030 1031
    # Create the target...
    my $target=[];
    target_init($target);
1032

1033
    if ($prj_target_type==$TT_GUIEXE or $prj_target_type==$TT_CUIEXE) {
1034 1035 1036
        $prj_name=lc($prj_name.".exe");
        @$target[$T_TYPE]=$opt_target_type;
        push @{@$target[$T_LDFLAGS]},(@$target[$T_TYPE] == $TT_CUIEXE ? "-mconsole" : "-mwindows");
1037 1038 1039 1040
    } elsif ($prj_target_type==$TT_LIB) {
        $prj_name=lc("lib".$prj_name.".a");
        @$target[$T_TYPE]=$TT_LIB;
        push @{@$target[$T_ARFLAGS]},("rc");
1041 1042 1043 1044
    } else {
        $prj_name=lc($prj_name.".dll");
        @$target[$T_TYPE]=$TT_DLL;
        my $canon=canonize($prj_name);
1045 1046 1047 1048 1049
        if (@$project_settings[$T_FLAGS] & $TF_HASDEF) {
            push @{@$target[$T_LDFLAGS]},("-shared","\$(${canon}_MODULE:.dll=.def)");
        } else {
            push @{@$target[$T_LDFLAGS]},("-shared","\$(${canon}_MODULE:.dll=.spec)");
        }
1050
    }
1051

1052 1053
    @$target[$T_NAME]=$prj_name;
    @$target[$T_FLAGS]|=@$project_settings[$T_FLAGS];
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    # This is the default link list of Visual Studio
    my @std_imports=qw(odbc32 ole32 oleaut32 winspool odbccp32);
    my @std_libraries=qw(uuid);
    if ((@$target[$T_FLAGS] & $TF_NODLLS) == 0) {
        @$target[$T_DLLS]=\@std_imports;
        @$target[$T_LIBRARIES]=\@std_libraries;
    } else {
        @$target[$T_DLLS]=[];
        @$target[$T_LIBRARIES]=[];
    }
    if ((@$target[$T_FLAGS] & $TF_NOMSVCRT) == 0) {
        push @{@$target[$T_LDFLAGS]},"-mno-cygwin";
1067 1068 1069
        if ($opt_arch != $OPT_ARCH_DEFAULT) {
            push @{@$target[$T_LDFLAGS]},"-m$opt_arch";
        }
1070 1071
    }
    push @{@$project[$P_TARGETS]},$target;
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    # Ask for target-specific options
    if ($opt_ask_target_options == $OPT_ASK_YES) {
        my $flag_desc="";
        if ((@$target[$T_FLAGS] & $TF_MFC)!=0) {
            $flag_desc=" (mfc";
        }
        if ($flag_desc ne "") {
            $flag_desc.=")";
        }
        print "* Specify any link option (-P/-i/-L/-l/--mfc) specific to the target\n";
        print "* \"$prj_name\"$flag_desc or 'never' to not be asked this question again:\n";
        while (1) {
        my $options=<STDIN>;
        chomp $options;
        if ($options eq "never") {
            $opt_ask_target_options=$OPT_ASK_NO;
            last;
        } elsif (source_set_options($target,$options)) {
            last;
        }
        print "Please re-enter the options:\n";
1094 1095
        }
    }
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    if (@$target[$T_FLAGS] & $TF_MFC) {
        @$project_settings[$T_FLAGS]|=$TF_MFC;
        push @{@$target[$T_DLL_PATH]},"\$(MFC_LIBRARY_PATH)";
        push @{@$target[$T_DLLS]},"mfc.dll";
        # FIXME: Link with the MFC in the Unix sense, until we
        # start exporting the functions properly.
        push @{@$target[$T_LIBRARY_PATH]},"\$(MFC_LIBRARY_PATH)";
        push @{@$target[$T_LIBRARIES]},"mfc";
    }

    # Match sources...
    push @{@$target[$T_SOURCES_C]},@{@$project_settings[$T_SOURCES_C]},@sources_c;
    @$project_settings[$T_SOURCES_C]=[];
    @sources_c=();
    push @{@$target[$T_SOURCES_CXX]},@{@$project_settings[$T_SOURCES_CXX]},@sources_cxx;
    @$project_settings[$T_SOURCES_CXX]=[];
    @sources_cxx=();
    push @{@$target[$T_SOURCES_RC]},@{@$project_settings[$T_SOURCES_RC]},@sources_rc;
    @$project_settings[$T_SOURCES_RC]=[];
    @sources_rc=();
    push @{@$target[$T_SOURCES_MISC]},@{@$project_settings[$T_SOURCES_MISC]},@sources_misc;
    @$project_settings[$T_SOURCES_MISC]=[];
    @sources_misc=();

    @$target[$T_SOURCES_C]=[sort @{@$target[$T_SOURCES_C]}];
    @$target[$T_SOURCES_CXX]=[sort @{@$target[$T_SOURCES_CXX]}];
    @$target[$T_SOURCES_RC]=[sort @{@$target[$T_SOURCES_RC]}];
    @$target[$T_SOURCES_MISC]=[sort @{@$target[$T_SOURCES_MISC]}];

1125 1126 1127 1128 1129 1130 1131
    if ($opt_ask_target_options == $OPT_ASK_SKIP) {
        $opt_ask_target_options=$OPT_ASK_YES;
    }

    if ((@$project_settings[$T_FLAGS] & $TF_NOMSVCRT) == 0) {
        push @{@$project_settings[$T_CEXTRA]},"-mno-cygwin";
        push @{@$project_settings[$T_CXXEXTRA]},"-mno-cygwin";
1132 1133 1134 1135
        if ($opt_arch != $OPT_ARCH_DEFAULT) {
            push @{@$project_settings[$T_CEXTRA]},"-m$opt_arch";
            push @{@$project_settings[$T_CXXEXTRA]},"-m$opt_arch";
        }
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    }

    if (@$project_settings[$T_FLAGS] & $TF_MFC) {
        push @{@$project_settings[$T_INCLUDE_PATH]},"\$(MFC_INCLUDE_PATH)";
    }
    # The sources that did not match, if any, go to the extra
    # source list of the project settings
    foreach my $source (@sources_c) {
        if ($source ne "") {
            push @{@$project_settings[$T_SOURCES_C]},$source;
        }
    }
    @$project_settings[$T_SOURCES_C]=[sort @{@$project_settings[$T_SOURCES_C]}];
    foreach my $source (@sources_cxx) {
        if ($source ne "") {
            push @{@$project_settings[$T_SOURCES_CXX]},$source;
        }
    }
    @$project_settings[$T_SOURCES_CXX]=[sort @{@$project_settings[$T_SOURCES_CXX]}];
    foreach my $source (@sources_rc) {
        if ($source ne "") {
            push @{@$project_settings[$T_SOURCES_RC]},$source;
        }
    }
    @$project_settings[$T_SOURCES_RC]=[sort @{@$project_settings[$T_SOURCES_RC]}];
    foreach my $source (@sources_misc) {
        if ($source ne "") {
            push @{@$project_settings[$T_SOURCES_MISC]},$source;
        }
    }
    @$project_settings[$T_SOURCES_MISC]=[sort @{@$project_settings[$T_SOURCES_MISC]}];
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
##
# Scans the specified workspace file to find the project files
sub source_scan_workspace_file($);
sub source_scan_workspace_file($)
{
    my $filename=$_[0];
    my $path=dirname($filename);
    my @components;

    if (! -e $filename) {
        return;
    }

    if (!open(FILEIWS,$filename)) {
        print STDERR "error: unable to open $filename for reading:\n";
        print STDERR "       $!\n";
        return;
    }

    my $prj_name;
    my $prj_path;

    if ($filename =~ /.dsw$/i) {
        while (<FILEIWS>) {
            # Remove any trailing CrLf
            s/\r\n$/\n/;

            # catch a project definition
1197
            if (/^Project:\s\"(.*)\"=(.*)\s-/) {
1198 1199
                $prj_name=$1;
                $prj_path=$2;
1200
                @components=split /[\/\\]+/, $prj_path;
1201 1202 1203 1204 1205 1206
                $prj_path=search_from($path, \@components);
                print "Name: $prj_name\nPath: $prj_path\n";
                source_scan_project_file(\@main_project,1,$prj_path);
                next;
            } elsif (/^#/) {
                # ignore Comments
1207 1208
            } elsif (/^Global:/) {
                # ignore the Global section
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
            } elsif (/\w:/) {
                print STDERR "unknown section $_\n";
            } elsif (/^Microsoft(.*)Studio(.*)File,\sFormat Version\s(.*)/) {
                print "\nFileversion: $3\n";
            }
        }
        close(FILEIWS);
    } elsif ($filename =~ /.sln$/i) {
        while (<FILEIWS>) {
            # Remove any trailing CrLf
            s/\r\n$/\n/;

            # catch a project definition
            if (/^Project(.*)=\s*"(.*)",\s*"(.*)",\s*"(.*)"/) {
                $prj_name=$2;
                $prj_path=$3;
1225
                if ($prj_path eq "Solution Items") { next; }
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
                @components=split /[\/\\]+/, $3;
                $prj_path=search_from($path, \@components);
                print "Name: $prj_name\nPath: $prj_path\n";
                source_scan_project_file(\@main_project,1,$prj_path);
                next;
            } elsif (/^Microsoft(.*)Studio(.*)File,\sFormat Version\s(.*)/) {
                print "\nFileversion: $3\n";
            }
        }
        close(FILEIWS);
    }

    @projects=sort { @$a[$P_PATH] cmp @$b[$P_PATH] } @projects;
}

1241 1242
##
# Scans the specified directory to:
1243
# - see if we should create a Makefile in this directory. We normally do
1244 1245 1246
#   so if we find a project file and sources
# - get a list of targets for this directory
# - get the list of source files
1247 1248
sub source_scan_directory($$$$);
sub source_scan_directory($$$$)
1249 1250 1251
{
  # a reference to the parent's project
  my $parent_project=$_[0];
1252
  # the full relative path to the current directory, including a
1253 1254 1255 1256 1257
  # trailing '/', or an empty string if this is the top level directory
  my $path=$_[1];
  # the name of this directory, including a trailing '/', or an empty
  # string if this is the top level directory
  my $dirname=$_[2];
1258
  # if set then no targets will be looked for and the sources will all
1259 1260
  # end up in the parent_project's 'misc' bucket
  my $no_target=$_[3];
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

  # reference to the project for this directory. May not be used
  my $project;
  # list of targets found in the 'current' directory
  my %targets;
  # list of sources found in the current directory
  my @sources_c=();
  my @sources_cxx=();
  my @sources_rc=();
  my @sources_misc=();
  # true if this directory contains a Windows project
  my $has_win_project=0;
1273 1274
  # true if this directory contains headers
  my $has_headers=0;
1275 1276
  # If we don't find any executable/library then we might make up targets
  # from the list of .dsp/.mak files we find since they usually have the
1277
  # same name as their target.
1278
  my @prj_files=();
1279 1280 1281
  my @mak_files=();

  if (defined $opt_single_target or $dirname eq "") {
1282 1283
    # Either there is a single target and thus a single project,
    # or we are in the top level directory for which a project
1284 1285 1286 1287
    # already exists
    $project=$parent_project;
  } else {
    $project=[];
1288
    project_init($project, $path, \@global_settings);
1289
  }
1290
  my $project_settings=@$project[$P_SETTINGS];
1291 1292 1293 1294

  # First find out what this directory contains:
  # collect all sources, targets and subdirectories
  my $directory=get_directory_contents($path);
1295
  foreach my $dentry (@$directory) {
1296 1297 1298 1299 1300 1301
    if ($dentry =~ /^\./) {
      next;
    }
    my $fullentry="$path$dentry";
    if (-d "$fullentry") {
      if ($dentry =~ /^(Release|Debug)/i) {
1302
	# These directories are often used to store the object files and the
1303
	# resulting executable/library. They should not contain anything else.
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        my @candidates=grep /\.(exe|dll|lib)$/i, @{get_directory_contents("$fullentry")};
        foreach my $candidate (sort @candidates) {
            my $dlldup = $candidate;
            $dlldup =~ s/\.lib$/.dll/;
            if ($candidate =~ /\.lib$/ and $targets{$dlldup})
            {
                # Often lib files are created together with dll files, even if the dll file is the
                # real target.
                next;
            }
            $targets{$candidate}=1;
        }
1316 1317 1318
      } elsif ($dentry =~ /^include/i) {
        # This directory must contain headers we're going to need
        push @{@$project_settings[$T_INCLUDE_PATH]},"-I$dentry";
1319
        source_scan_directory($project,"$fullentry/","$dentry/",1);
1320
      } else {
1321 1322
	# Recursively scan this directory. Any source file that cannot be
	# attributed to a project in one of the subdirectories will be
1323 1324
	# attributed to this project.
	source_scan_directory($project,"$fullentry/","$dentry/",$no_target);
1325 1326
      }
    } elsif (-f "$fullentry") {
1327
      if ($dentry =~ /\.(exe|dll|lib)$/i) {
1328
	$targets{$dentry}=1;
1329
      } elsif ($dentry =~ /\.c$/i and $dentry !~ /\.(dbg|spec)\.c$/) {
1330
	push @sources_c,"$dentry";
1331
      } elsif ($dentry =~ /\.cpp$/i) {
1332
	if ($dentry =~ /^stdafx.cpp$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
1333
	  push @sources_misc,"$dentry";
1334
	  @$project_settings[$T_FLAGS]|=$TF_MFC;
1335 1336 1337
	} else {
	  push @sources_cxx,"$dentry";
	}
1338 1339 1340
      } elsif ($dentry =~ /\.cxx$/i) {
          @$project_settings[$T_FLAGS]|=$TF_HASCXX;
          push @sources_cxx,"$dentry";
1341 1342
      } elsif ($dentry =~ /\.rc$/i) {
	push @sources_rc,"$dentry";
1343 1344
      } elsif ($dentry =~ /\.def$/i) {
	@$project_settings[$T_FLAGS]|=$TF_HASDEF;
1345
      } elsif ($dentry =~ /\.(h|hxx|hpp|inl|rc2|dlg)$/i) {
1346
	$has_headers=1;
1347
	push @sources_misc,"$dentry";
1348
	if ($dentry =~ /^stdafx.h$/i && !(@$project_settings[$T_FLAGS] & $TF_NOMFC)) {
1349
	  @$project_settings[$T_FLAGS]|=$TF_MFC;
1350
	}
1351 1352
      } elsif ($dentry =~ /\.(dsp|vcproj)$/i) {
	push @prj_files,"$dentry";
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
	$has_win_project=1;
      } elsif ($dentry =~ /\.mak$/i) {
	push @mak_files,"$dentry";
	$has_win_project=1;
      } elsif ($dentry =~ /^makefile/i) {
	$has_win_project=1;
      }
    }
  }

1363 1364 1365
  if ($has_headers) {
    push @{@$project_settings[$T_INCLUDE_PATH]},"-I.";
  }
1366
  # If we have a single target then all we have to do is assign
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  # all the sources to it and we're done
  # FIXME: does this play well with the --interactive mode?
  if ($opt_single_target) {
    my $target=@{@$project[$P_TARGETS]}[0];
    push @{@$target[$T_SOURCES_C]},map "$path$_",@sources_c;
    push @{@$target[$T_SOURCES_CXX]},map "$path$_",@sources_cxx;
    push @{@$target[$T_SOURCES_RC]},map "$path$_",@sources_rc;
    push @{@$target[$T_SOURCES_MISC]},map "$path$_",@sources_misc;
    return;
  }
1377 1378 1379 1380 1381 1382
  if ($no_target) {
    my $parent_settings=@$parent_project[$P_SETTINGS];
    push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_c;
    push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_cxx;
    push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_rc;
    push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_misc;
1383
    push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@{@$project_settings[$T_SOURCES_MISC]};
1384 1385
    return;
  }
1386 1387 1388 1389 1390 1391 1392 1393

  my $source_count=@sources_c+@sources_cxx+@sources_rc+
                   @{@$project_settings[$T_SOURCES_C]}+
                   @{@$project_settings[$T_SOURCES_CXX]}+
                   @{@$project_settings[$T_SOURCES_RC]};
  if ($source_count == 0) {
    # A project without real sources is not a project, get out!
    if ($project!=$parent_project) {
1394
      my $parent_settings=@$parent_project[$P_SETTINGS];
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
      push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_misc;
      push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@{@$project_settings[$T_SOURCES_MISC]};
    }
    return;
  }
  #print "targets=",%targets,"\n";
  #print "target_count=$target_count\n";
  #print "has_win_project=$has_win_project\n";
  #print "dirname=$dirname\n";

  my $target_count;
  if (($has_win_project != 0) or ($dirname eq "")) {
1407
    # Deal with cases where we could not find any executable/library, and
1408 1409 1410 1411 1412
    # thus have no target, although we did find some sort of windows project.
    $target_count=keys %targets;
    if ($target_count == 0) {
      # Try to come up with a target list based on .dsp/.mak files
      my $prj_list;
1413
      if (@prj_files > 0) {
1414
        print "Projectfile found! You might want to try using it directly.\n";
1415
        $prj_list=\@prj_files;
1416
      } else {
1417
        $prj_list=\@mak_files;
1418
      }
1419
      foreach my $filename (@$prj_list) {
1420
	$filename =~ s/\.(dsp|vcproj|mak)$//i;
1421
	if ($opt_target_type == $TT_DLL) {
1422
	  $filename = "$filename.dll";
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
	}
	$targets{$filename}=1;
      }
      $target_count=keys %targets;
      if ($target_count == 0) {
	# Still nothing, try the name of the directory
	my $name;
	if ($dirname eq "") {
	  # Bad luck, this is the top level directory!
	  $name=(split /\//, cwd)[-1];
	} else {
	  $name=$dirname;
1435
	  # Remove the trailing '/'. Also eliminate whatever is after the last
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
	  # '.' as it is likely to be meaningless (.orig, .new, ...)
	  $name =~ s+(/|\.[^.]*)$++;
	  if ($name eq "src") {
	    # 'src' is probably a subdirectory of the real project directory.
	    # Try again with the parent (if any).
	    my $parent=$path;
	    if ($parent =~ s+([^/]*)/[^/]*/$+$1+) {
	      $name=$parent;
	    } else {
	      $name=(split /\//, cwd)[-1];
	    }
	  }
	}
	$name =~ s+(/|\.[^.]*)$++;
	if ($opt_target_type == $TT_DLL) {
1451
	  $name = canonize($name).".dll";
1452 1453
	} elsif ($opt_target_type == $TT_LIB) {
	  $name = "lib".canonize($name).".a";
1454
	} else {
1455
	  $name = canonize($name).".exe";
1456 1457 1458 1459 1460 1461 1462 1463
	}
	$targets{$name}=1;
      }
    }

    # Ask confirmation to the user if he wishes so
    if ($opt_is_interactive == $OPT_ASK_YES) {
      my $target_list=join " ",keys %targets;
1464
      print "\n*** In ",($path?$path:"./"),"\n";
1465 1466 1467 1468 1469 1470
      print "* winemaker found the following list of (potential) targets\n";
      print "*   $target_list\n";
      print "* Type enter to use it as is, your own comma-separated list of\n";
      print "* targets, 'none' to assign the source files to a parent directory,\n";
      print "* or 'ignore' to ignore everything in this directory tree.\n";
      print "* Target list:\n";
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
      $target_list=<STDIN>;
      chomp $target_list;
      if ($target_list eq "") {
	# Keep the target list as is, i.e. do nothing
      } elsif ($target_list eq "none") {
	# Empty the target list
	undef %targets;
      } elsif ($target_list eq "ignore") {
	# Ignore this subtree altogether
	return;
      } else {
	undef %targets;
1483
	foreach my $target (split /,/,$target_list) {
1484 1485 1486 1487 1488 1489 1490 1491
	  $target =~ s+^\s*++;
	  $target =~ s+\s*$++;
	  $targets{$target}=1;
	}
      }
    }
  }

1492
  # If we have no project at this level, then transfer all
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
  # the sources to the parent project
  $target_count=keys %targets;
  if ($target_count == 0) {
    if ($project!=$parent_project) {
      my $parent_settings=@$parent_project[$P_SETTINGS];
      push @{@$parent_settings[$T_SOURCES_C]},map "$dirname$_",@sources_c;
      push @{@$parent_settings[$T_SOURCES_CXX]},map "$dirname$_",@sources_cxx;
      push @{@$parent_settings[$T_SOURCES_RC]},map "$dirname$_",@sources_rc;
      push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@sources_misc;
      push @{@$parent_settings[$T_SOURCES_MISC]},map "$dirname$_",@{@$project_settings[$T_SOURCES_MISC]};
    }
    return;
  }

1507
  # Otherwise add this project to the project list, except for
1508 1509 1510 1511 1512 1513 1514
  # the main project which is already in the list.
  if ($dirname ne "") {
    push @projects,$project;
  }

  # Ask for project-wide options
  if ($opt_ask_project_options == $OPT_ASK_YES) {
1515 1516 1517 1518
    my $flag_desc="";
    if ((@$project_settings[$T_FLAGS] & $TF_MFC)!=0) {
      $flag_desc="mfc";
    }
1519
    print "* Type any project-wide options (-D/-I/-P/-i/-L/-l/--mfc),\n";
1520 1521 1522 1523 1524
    if (defined $flag_desc) {
      print "* (currently $flag_desc)\n";
    }
    print "* or 'skip' to skip the target specific options,\n";
    print "* or 'never' to not be asked this question again:\n";
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    while (1) {
      my $options=<STDIN>;
      chomp $options;
      if ($options eq "skip") {
        $opt_ask_target_options=$OPT_ASK_SKIP;
        last;
      } elsif ($options eq "never") {
        $opt_ask_project_options=$OPT_ASK_NO;
        last;
      } elsif (source_set_options($project_settings,$options)) {
        last;
      }
      print "Please re-enter the options:\n";
1538 1539 1540 1541 1542
    }
  }

  # - Create the targets
  # - Check if we have both libraries and programs
1543
  # - Match each target with source files (sort in reverse
1544
  #   alphabetical order to get the longest matches first)
1545
  my @local_dlls=();
1546
  my @local_libs=();
1547
  my @local_depends=();
1548
  my @exe_list=();
1549
  foreach my $target_name (map (lc, (sort { $b cmp $a } keys %targets))) {
1550 1551 1552 1553
    # Create the target...
    my $target=[];
    target_init($target);
    @$target[$T_NAME]=$target_name;
1554
    @$target[$T_FLAGS]|=@$project_settings[$T_FLAGS];
1555
    if ($target_name =~ /\.dll$/) {
1556
      @$target[$T_TYPE]=$TT_DLL;
1557 1558
      push @local_depends,"$target_name.so";
      push @local_dlls,$target_name;
Francois Gouget's avatar
Francois Gouget committed
1559
      my $canon=canonize($target_name);
1560 1561 1562 1563 1564
      if (@$project_settings[$T_FLAGS] & $TF_HASDEF) {
          push @{@$target[$T_LDFLAGS]},("-shared","\$(${canon}_MODULE:.dll=.def)");
      } else {
          push @{@$target[$T_LDFLAGS]},("-shared","\$(${canon}_MODULE:.dll=.spec)");
      }
1565 1566 1567 1568 1569 1570 1571
    } elsif ($target_name =~ /\.lib$/) {
      $target_name =~ s/(.*)\.lib/lib$1.a/;
      @$target[$T_NAME]=$target_name;
      @$target[$T_TYPE]=$TT_LIB;
      push @local_depends,"$target_name";
      push @local_libs,$target_name;
      push @{@$target[$T_ARFLAGS]},("rc");
1572 1573 1574 1575 1576 1577
    } elsif ($target_name =~ /\.a$/) {
      @$target[$T_NAME]=$target_name;
      @$target[$T_TYPE]=$TT_LIB;
      push @local_depends,"$target_name";
      push @local_libs,$target_name;
      push @{@$target[$T_ARFLAGS]},("rc");
1578 1579
    } else {
      @$target[$T_TYPE]=$opt_target_type;
1580
      push @exe_list,$target;
1581
      push @{@$target[$T_LDFLAGS]},(@$target[$T_TYPE] == $TT_CUIEXE ? "-mconsole" : "-mwindows");
1582
    }
1583 1584
    my $basename=$target_name;
    $basename=~ s/\.(dll|exe)$//i;
1585 1586
    # This is the default link list of Visual Studio
    my @std_imports=qw(odbc32 ole32 oleaut32 winspool odbccp32);
1587
    my @std_libraries=qw(uuid);
1588
    if ((@$target[$T_FLAGS] & $TF_NODLLS) == 0) {
1589
      @$target[$T_DLLS]=\@std_imports;
1590
      @$target[$T_LIBRARIES]=\@std_libraries;
1591 1592
    } else {
      @$target[$T_DLLS]=[];
1593
      @$target[$T_LIBRARIES]=[];
1594
    }
1595 1596
    if ((@$target[$T_FLAGS] & $TF_NOMSVCRT) == 0) {
      push @{@$target[$T_LDFLAGS]},"-mno-cygwin";
1597 1598 1599
      if ($opt_arch != $OPT_ARCH_DEFAULT) {
        push @{@$target[$T_LDFLAGS]},"-m$opt_arch";
      }
1600
    }
1601 1602 1603 1604
    push @{@$project[$P_TARGETS]},$target;

    # Ask for target-specific options
    if ($opt_ask_target_options == $OPT_ASK_YES) {
1605 1606 1607 1608 1609 1610 1611
      my $flag_desc="";
      if ((@$target[$T_FLAGS] & $TF_MFC)!=0) {
	$flag_desc=" (mfc";
      }
      if ($flag_desc ne "") {
	$flag_desc.=")";
      }
1612
      print "* Specify any link option (-P/-i/-L/-l/--mfc) specific to the target\n";
1613
      print "* \"$target_name\"$flag_desc or 'never' to not be asked this question again:\n";
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
      while (1) {
        my $options=<STDIN>;
        chomp $options;
        if ($options eq "never") {
          $opt_ask_target_options=$OPT_ASK_NO;
          last;
        } elsif (source_set_options($target,$options)) {
          last;
        }
        print "Please re-enter the options:\n";
1624 1625 1626 1627
      }
    }
    if (@$target[$T_FLAGS] & $TF_MFC) {
      @$project_settings[$T_FLAGS]|=$TF_MFC;
1628 1629
      push @{@$target[$T_DLL_PATH]},"\$(MFC_LIBRARY_PATH)";
      push @{@$target[$T_DLLS]},"mfc.dll";
1630
      # FIXME: Link with the MFC in the Unix sense, until we
1631
      # start exporting the functions properly.
1632
      push @{@$target[$T_LIBRARY_PATH]},"\$(MFC_LIBRARY_PATH)";
1633
      push @{@$target[$T_LIBRARIES]},"mfc";
1634 1635 1636 1637
    }

    # Match sources...
    if ($target_count == 1) {
1638 1639
      push @{@$target[$T_SOURCES_C]},@{@$project_settings[$T_SOURCES_C]},@sources_c;
      @$project_settings[$T_SOURCES_C]=[];
1640
      @sources_c=();
1641 1642 1643

      push @{@$target[$T_SOURCES_CXX]},@{@$project_settings[$T_SOURCES_CXX]},@sources_cxx;
      @$project_settings[$T_SOURCES_CXX]=[];
1644
      @sources_cxx=();
1645 1646 1647

      push @{@$target[$T_SOURCES_RC]},@{@$project_settings[$T_SOURCES_RC]},@sources_rc;
      @$project_settings[$T_SOURCES_RC]=[];
1648
      @sources_rc=();
1649 1650 1651 1652

      push @{@$target[$T_SOURCES_MISC]},@{@$project_settings[$T_SOURCES_MISC]},@sources_misc;
      # No need for sorting these sources
      @$project_settings[$T_SOURCES_MISC]=[];
1653 1654
      @sources_misc=();
    } else {
1655
      foreach my $source (@sources_c) {
1656 1657 1658 1659 1660
	if ($source =~ /^$basename/i) {
	  push @{@$target[$T_SOURCES_C]},$source;
	  $source="";
	}
      }
1661
      foreach my $source (@sources_cxx) {
1662 1663 1664 1665 1666
	if ($source =~ /^$basename/i) {
	  push @{@$target[$T_SOURCES_CXX]},$source;
	  $source="";
	}
      }
1667
      foreach my $source (@sources_rc) {
1668 1669 1670 1671 1672
	if ($source =~ /^$basename/i) {
	  push @{@$target[$T_SOURCES_RC]},$source;
	  $source="";
	}
      }
1673
      foreach my $source (@sources_misc) {
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
	if ($source =~ /^$basename/i) {
	  push @{@$target[$T_SOURCES_MISC]},$source;
	  $source="";
	}
      }
    }
    @$target[$T_SOURCES_C]=[sort @{@$target[$T_SOURCES_C]}];
    @$target[$T_SOURCES_CXX]=[sort @{@$target[$T_SOURCES_CXX]}];
    @$target[$T_SOURCES_RC]=[sort @{@$target[$T_SOURCES_RC]}];
    @$target[$T_SOURCES_MISC]=[sort @{@$target[$T_SOURCES_MISC]}];
  }
  if ($opt_ask_target_options == $OPT_ASK_SKIP) {
    $opt_ask_target_options=$OPT_ASK_YES;
  }

1689
  if ((@$project_settings[$T_FLAGS] & $TF_NOMSVCRT) == 0) {
1690 1691
    push @{@$project_settings[$T_CEXTRA]},"-mno-cygwin";
    push @{@$project_settings[$T_CXXEXTRA]},"-mno-cygwin";
1692 1693 1694 1695
      if ($opt_arch != $OPT_ARCH_DEFAULT) {
        push @{@$project_settings[$T_CEXTRA]},"-m$opt_arch";
        push @{@$project_settings[$T_CXXEXTRA]},"-m$opt_arch";
      }
1696 1697
  }

1698 1699 1700
  if (@$project_settings[$T_FLAGS] & $TF_MFC) {
    push @{@$project_settings[$T_INCLUDE_PATH]},"\$(MFC_INCLUDE_PATH)";
  }
1701
  # The sources that did not match, if any, go to the extra
1702
  # source list of the project settings
1703
  foreach my $source (@sources_c) {
1704 1705 1706 1707 1708
    if ($source ne "") {
      push @{@$project_settings[$T_SOURCES_C]},$source;
    }
  }
  @$project_settings[$T_SOURCES_C]=[sort @{@$project_settings[$T_SOURCES_C]}];
1709
  foreach my $source (@sources_cxx) {
1710 1711 1712 1713 1714
    if ($source ne "") {
      push @{@$project_settings[$T_SOURCES_CXX]},$source;
    }
  }
  @$project_settings[$T_SOURCES_CXX]=[sort @{@$project_settings[$T_SOURCES_CXX]}];
1715
  foreach my $source (@sources_rc) {
1716 1717 1718 1719 1720
    if ($source ne "") {
      push @{@$project_settings[$T_SOURCES_RC]},$source;
    }
  }
  @$project_settings[$T_SOURCES_RC]=[sort @{@$project_settings[$T_SOURCES_RC]}];
1721
  foreach my $source (@sources_misc) {
1722 1723 1724 1725 1726 1727
    if ($source ne "") {
      push @{@$project_settings[$T_SOURCES_MISC]},$source;
    }
  }
  @$project_settings[$T_SOURCES_MISC]=[sort @{@$project_settings[$T_SOURCES_MISC]}];

1728 1729
  # Finally if we are building both libraries and programs in
  # this directory, then the programs should be linked with all
1730
  # the libraries
1731
  if (@local_dlls > 0 and @exe_list > 0) {
1732
    foreach my $target (@exe_list) {
1733
      push @{@$target[$T_DLL_PATH]},"-L.";
1734
      push @{@$target[$T_DLLS]},@local_dlls;
1735 1736
    }
  }
1737 1738 1739 1740 1741 1742
  if (@local_libs > 0 and @exe_list > 0) {
    foreach my $target (@exe_list) {
      push @{@$target[$T_LIBRARY_PATH]},"-L.";
      push @{@$target[$T_LIBRARIES]},@local_libs;
    }
  }
1743 1744 1745 1746
}

##
# Scan the source directories in search of things to build
1747
sub source_scan()
1748 1749 1750
{
  # If there's a single target then this is going to be the default target
  if (defined $opt_single_target) {
1751 1752 1753
    # Create the main target
    my $main_target=[];
    target_init($main_target);
1754
    @$main_target[$T_NAME]=$opt_single_target;
1755
    @$main_target[$T_TYPE]=$opt_target_type;
1756 1757 1758

    # Add it to the list
    push @{$main_project[$P_TARGETS]},$main_target;
1759 1760 1761 1762 1763
  }

  # The main directory is always going to be there
  push @projects,\@main_project;

1764 1765 1766 1767 1768 1769 1770 1771
    if (defined $opt_work_dir) {
        # Now scan the directory tree looking for source files and, maybe, targets
        print "Scanning the source directories...\n";
        source_scan_directory(\@main_project,"","",0);
        @projects=sort { @$a[$P_PATH] cmp @$b[$P_PATH] } @projects;
    } elsif (defined $opt_work_file) {
        if ($opt_work_file =~ /.dsp$/i or $opt_work_file =~ /.vcproj$/i) {
            source_scan_project_file(\@main_project,0,$opt_work_file);
1772 1773
        } elsif ($opt_work_file =~ /.dsw$/i or $opt_work_file =~ /.sln$/i) {
            source_scan_workspace_file($opt_work_file);
1774 1775
        }
    }
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
}

#####
#
# Source search
#
#####

##
# Performs a directory traversal and renames the files so that:
# - they have the case desired by the user
# - their extension is of the appropriate case
# - they don't contain annoying characters like ' ', '$', '#', ...
1789
# But only perform these changes for source files and directories.
1790 1791
sub fix_file_and_directory_names($);
sub fix_file_and_directory_names($)
1792 1793 1794
{
  my $dirname=$_[0];

1795 1796 1797
  my $directory=get_directory_contents($dirname);
  foreach my $dentry (@$directory)
  {
1798
      if ($dentry =~ /^\./ or $dentry eq "CVS") {
1799
          next;
1800 1801
      }
      # Set $warn to 1 if the user should be warned of the renaming
1802
      my $warn;
1803 1804
      my $new_name=$dentry;

1805 1806
      if (-f "$dirname/$dentry")
      {
1807 1808 1809 1810 1811
          # Don't rename Winemaker's makefiles
          next if ($dentry eq "Makefile" and
                   `head -n 1 "$dirname/$dentry"` =~ /Generated by Winemaker/);

          # Leave non-source files alone
1812
          next if ($new_name !~ /(^makefile|\.(c|cpp|h|rc|spec|def))$/i);
1813 1814

          # Only all lowercase extensions are supported (because of
1815
          # rules like '.c.o:').
1816 1817 1818 1819
          $new_name =~ s/\.C$/.c/;
          $new_name =~ s/\.cpp$/.cpp/i;
          $warn=1 if ($new_name =~ s/\.cxx$/.cpp/i);
          $new_name =~ s/\.rc$/.rc/i;
1820
          # And this last one is to avoid confusion when running make
1821
          $warn=1 if ($new_name =~ s/^makefile$/makefile.win/i);
1822 1823 1824
      }

      # Adjust the case to the user's preferences
1825
      if (($opt_lower == $OPT_LOWER_ALL and $dentry =~ /[A-Z]/) or
1826 1827
          ($opt_lower == $OPT_LOWER_UPPERCASE and $dentry !~ /[a-z]/)
         ) {
1828
          $new_name=lc $new_name;
1829 1830
      }

1831
      # make doesn't support these characters well
1832 1833
      $new_name =~ s/[ \$]/_/g;

1834
      # And finally, perform the renaming
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
      if ($new_name ne $dentry)
      {
          if ($warn) {
              print STDERR "warning: in \"$dirname\", renaming \"$dentry\" to \"$new_name\"\n";
          }
          if (!rename("$dirname/$dentry","$dirname/$new_name")) {
              print STDERR "error: in \"$dirname\", unable to rename \"$dentry\" to \"$new_name\"\n";
              print STDERR "       $!\n";
              $new_name=$dentry;
          }
          else
          {
              clear_directory_cache($dirname);
          }
1849 1850
      }
      if (-d "$dirname/$new_name") {
1851
          fix_file_and_directory_names("$dirname/$new_name");
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
      }
  }
}



#####
#
# Source fixup
#
#####

##
1865 1866
# Try to find a file for the specified filename. The attempt is
# case-insensitive which is why it's not trivial. If a match is
1867
# found then we return the pathname with the correct case.
1868
sub search_from($$)
1869 1870 1871 1872 1873
{
  my $dirname=$_[0];
  my $path=$_[1];
  my $real_path="";

1874
  $dirname =~ s/(\.\/)+//;
1875
  if ($dirname eq "" or $dirname eq "." or $dirname eq "./") {
1876
    $dirname=cwd;
Francois Gouget's avatar
Francois Gouget committed
1877
  } elsif ($dirname !~ m+^/+) {
1878 1879 1880 1881 1882 1883
    $dirname=cwd . "/" . $dirname;
  }
  if ($dirname !~ m+/$+) {
    $dirname.="/";
  }

1884
  foreach my $component (@$path) {
1885 1886
    $component=~s/^\"//;
    $component=~s/\"$//;
1887
    #print "    looking for $component in \"$dirname\"\n";
1888 1889 1890 1891 1892
    if ($component eq ".") {
      # Pass it as is
      $real_path.="./";
    } elsif ($component eq "..") {
      # Go up one level
1893 1894 1895 1896 1897
      if ($dirname =~ /\.\.\/$/) {
        $dirname.="../";
      } else {
        $dirname=dirname($dirname) . "/";
      }
1898 1899
      $real_path.="../";
    } else {
1900
      # The file/directory may have been renamed before. Also try to
1901 1902 1903 1904 1905 1906 1907
      # match the renamed file.
      my $renamed=$component;
      $renamed =~ s/[ \$]/_/g;
      if ($renamed eq $component) {
        undef $renamed;
      }

1908 1909
      my $directory=get_directory_contents $dirname;
      my $found;
1910
      foreach my $dentry (@$directory) {
1911
	if ($dentry =~ /^\Q$component\E$/i or
1912 1913
            (defined $renamed and $dentry =~ /^$renamed$/i)
           ) {
1914 1915 1916 1917 1918 1919 1920 1921
	  $dirname.="$dentry/";
	  $real_path.="$dentry/";
	  $found=1;
	  last;
	}
      }
      if (!defined $found) {
	# Give up
1922
	#print "    could not find $component in $dirname\n";
1923 1924 1925 1926 1927
	return;
      }
    }
  }
  $real_path=~ s+/$++;
1928
  #print "    -> found $real_path\n";
1929 1930 1931 1932
  return $real_path;
}

##
1933
# Performs a case-insensitive search for the specified file in the
1934 1935 1936 1937 1938 1939
# include path.
# $line is the line number that should be referenced when an error occurs
# $filename is the file we are looking for
# $dirname is the directory of the file containing the '#include' directive
#    if '"' was used, it is an empty string otherwise
# $project and $target specify part of the include path
1940
sub get_real_include_name($$$$$)
1941 1942 1943 1944 1945 1946 1947
{
  my $line=$_[0];
  my $filename=$_[1];
  my $dirname=$_[2];
  my $project=$_[3];
  my $target=$_[4];

1948
  if ($filename =~ /^([a-zA-Z]:)?[\/\\]/ or $filename =~ /^[a-zA-Z]:[\/\\]?/) {
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
    # This is not a relative path, we cannot make any check
    my $warning="path:$filename";
    if (!defined $warnings{$warning}) {
      $warnings{$warning}="1";
      print STDERR "warning: cannot check the case of absolute pathnames:\n";
      print STDERR "$line:   $filename\n";
    }
  } else {
    # Here's how we proceed:
    # - split the filename we look for into its components
    # - then for each directory in the include path
    #   - trace the directory components starting from that directory
1961
    #   - if we fail to find a match at any point then continue with
1962 1963 1964
    #     the next directory in the include path
    #   - otherwise, rejoice, our quest is over.
    my @file_components=split /[\/\\]+/, $filename;
1965
    #print "  Searching for $filename from @$project[$P_PATH]\n";
1966 1967 1968

    my $real_filename;
    if ($dirname ne "") {
1969 1970
      # This is an 'include ""' -> look in dirname first.
      #print "    in $dirname (include \"\")\n";
1971 1972 1973 1974 1975 1976
      $real_filename=search_from($dirname,\@file_components);
      if (defined $real_filename) {
	return $real_filename;
      }
    }
    my $project_settings=@$project[$P_SETTINGS];
1977
    foreach my $include (@{@$target[$T_INCLUDE_PATH]}, @{@$project_settings[$T_INCLUDE_PATH]}) {
1978 1979
      my $dirname=$include;
      $dirname=~ s+^-I++;
1980
      $dirname=~ s+\s$++;
1981 1982 1983
      if (!is_absolute($dirname)) {
	$dirname="@$project[$P_PATH]$dirname";
      } else {
1984 1985
        $dirname=~ s+^\$\(TOPSRCDIR\)/++;
        $dirname=~ s+^\$\(SRCDIR\)/+@$project[$P_PATH]+;
1986 1987
      }
      #print "    in $dirname\n";
1988 1989 1990 1991 1992 1993 1994
      $real_filename=search_from("$dirname",\@file_components);
      if (defined $real_filename) {
	return $real_filename;
      }
    }
    my $dotdotpath=@$project[$P_PATH];
    $dotdotpath =~ s/[^\/]+/../g;
1995
    foreach my $include (@{$global_settings[$T_INCLUDE_PATH]}) {
1996 1997 1998
      my $dirname=$include;
      $dirname=~ s+^-I++;
      $dirname=~ s+^\$\(TOPSRCDIR\)\/++;
1999
      $dirname=~ s+^\$\(SRCDIR\)\/+@$project[$P_PATH]+;
2000
      #print "    in $dirname  (global setting)\n";
2001 2002 2003 2004 2005 2006 2007 2008
      $real_filename=search_from("$dirname",\@file_components);
      if (defined $real_filename) {
	return $real_filename;
      }
    }
  }
  $filename =~ s+\\\\+/+g; # in include ""
  $filename =~ s+\\+/+g; # in include <> !
2009
  if ($opt_lower_include) {
2010 2011 2012 2013 2014
    return lc "$filename";
  }
  return $filename;
}

2015
sub print_pack($$$)
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
{
  my $indent=$_[0];
  my $size=$_[1];
  my $trailer=$_[2];

  if ($size =~ /^(1|2|4|8)$/) {
    print FILEO "$indent#include <pshpack$size.h>$trailer";
  } else {
    print FILEO "$indent/* winemaker:warning: Unknown size \"$size\". Defaulting to 4 */\n";
    print FILEO "$indent#include <pshpack4.h>$trailer";
  }
}

2029
##
2030 2031 2032 2033 2034
# 'Parses' a source file and fixes constructs that would not work with
# Winelib. The parsing is rather simple and not all non-portable features
# are corrected. The most important feature that is corrected is the case
# and path separator of '#include' directives. This requires that each
# source file be associated to a project & target so that the proper
2035
# include path is used.
2036
# Also note that the include path is relative to the directory in which the
2037
# compiler is run, i.e. that of the project, not to that of the file.
2038
sub fix_file($$$)
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
{
  my $filename=$_[0];
  my $project=$_[1];
  my $target=$_[2];
  $filename="@$project[$P_PATH]$filename";
  if (! -e $filename) {
    return;
  }

  my $is_rc=($filename =~ /\.(rc2?|dlg)$/i);
  my $dirname=dirname($filename);
  my $is_mfc=0;
  if (defined $target and (@$target[$T_FLAGS] & $TF_MFC)) {
    $is_mfc=1;
  }

  print "  $filename\n";
  if (! -e "$filename.bak") {
    if (!copy("$filename","$filename.bak")) {
      print STDERR "error: unable to make a backup of $filename:\n";
      print STDERR "       $!\n";
      return;
    }
  }
  if (!open(FILEI,"$filename.bak")) {
    print STDERR "error: unable to open $filename.bak for reading:\n";
    print STDERR "       $!\n";
    return;
  }
  if (!open(FILEO,">$filename")) {
    print STDERR "error: unable to open $filename for writing:\n";
    print STDERR "       $!\n";
    return;
  }
  my $line=0;
  my $modified=0;
  my $rc_block_depth=0;
  my $rc_textinclude_state=0;
2077
  my @pack_stack;
2078
  while (<FILEI>) {
2079 2080 2081 2082 2083
    # Remove any trailing CtrlZ, which isn't strictly in the file
    if (/\x1A/) {
      s/\x1A//;
      last if (/^$/)
    }
2084
    $line++;
2085 2086 2087 2088 2089
    s/\r\n$/\n/;
    if (!/\n$/) {
      # Make sure all files are '\n' terminated
      $_ .= "\n";
    }
2090
    if ($is_rc and !$is_mfc and /^(\s*)(\#\s*include\s*)\"afxres\.h\"/) {
2091 2092
      # VC6 automatically includes 'afxres.h', an MFC specific header, in
      # the RC files it generates (even in non-MFC projects). So we replace
2093
      # it with 'winresrc.h' its very close standard cousin so that non MFC
2094
      # projects can compile in Wine without the MFC sources.
2095 2096 2097
      my $warning="mfc:afxres.h";
      if (!defined $warnings{$warning}) {
	$warnings{$warning}="1";
2098
	print STDERR "warning: In non-MFC projects, winemaker replaces the MFC specific header 'afxres.h' with 'winresrc.h'\n";
2099 2100
	print STDERR "warning: the above warning is issued only once\n";
      }
2101
      print FILEO "$1/* winemaker: $2\"afxres.h\" */\n";
2102 2103
      print FILEO "$1/* winemaker:warning: 'afxres.h' is an MFC specific header. Replacing it with 'winresrc.h' */\n";
      print FILEO "$1$2\"winresrc.h\"$'";
2104
      $modified=1;
2105

2106 2107 2108 2109 2110
    } elsif (/^(\s*\#\s*include\s*)([\"<])([^\"]+)([\">])/) {
      my $from_file=($2 eq "<"?"":$dirname);
      my $real_include_name=get_real_include_name($line,$3,$from_file,$project,$target);
      print FILEO "$1$2$real_include_name$4$'";
      $modified|=($real_include_name ne $3);
2111

2112 2113 2114 2115 2116
    } elsif (/^(\s*)\#\s*pragma\s+comment\s*\(\s*lib\s*,\s*\"(\w+)\.lib\"\s*\)/) {
      my $pragma_indent=$1;
      my $pragma_lib=$2;
      push @{@$target[$T_LIBRARIES]},$pragma_lib;
      print FILEO "$pragma_indent/* winemaker: Added -l$pragma_lib to the libraries */\n";
2117 2118 2119
    } elsif (s/^(\s*)(\#\s*pragma\s+pack\s*\(\s*)//) {
      # Pragma pack handling
      #
2120 2121
      # pack_stack is an array of references describing the stack of
      # pack directives currently in effect. Each directive if described
2122 2123 2124
      # by a reference to an array containing:
      # - "push" for pack(push,...) directives, "" otherwise
      # - the directive's identifier at index 1
2125
      # - the directive's alignment value at index 2
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
      #
      # Don't believe a word of what the documentation says: it's all wrong.
      # The code below is based on the actual behavior of Visual C/C++ 6.
      my $pack_indent=$1;
      my $pack_header=$2;
      if (/^(\))/) {
        # pragma pack()
        # Pushes the default stack alignment
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        print FILEO "$pack_indent/* winemaker:warning: Using 4 as the default alignment */\n";
        print_pack($pack_indent,4,$');
        push @pack_stack, [ "", "", 4 ];

      } elsif (/^(pop\s*(,\s*\d+\s*)?\))/) {
        # pragma pack(pop)
        # pragma pack(pop,n)
        # Goes up the stack until it finds a pack(push,...), and pops it
        # Ignores any pack(n) entry
        # Issues a warning if the pack is of the form pack(push,label)
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        my $pack_comment=$';
2147
        $pack_comment =~ s/^\s*//;
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        if ($pack_comment ne "") {
          print FILEO "$pack_indent$pack_comment";
        }
        while (1) {
          my $alignment=pop @pack_stack;
          if (!defined $alignment) {
            print FILEO "$pack_indent/* winemaker:warning: No pack(push,...) found. All the stack has been popped */\n";
            last;
          }
          if (@$alignment[1]) {
            print FILEO "$pack_indent/* winemaker:warning: Anonymous pop of pack(push,@$alignment[1]) (@$alignment[2]) */\n";
          }
          print FILEO "$pack_indent#include <poppack.h>\n";
          if (@$alignment[0]) {
            last;
          }
        }

      } elsif (/^(pop\s*,\s*(\w+)\s*(,\s*\d+\s*)?\))/) {
        # pragma pack(pop,label[,n])
        # Goes up the stack until finding a pack(push,...) and pops it.
        # 'n', if specified, is ignored.
        # Ignores any pack(n) entry
        # Issues a warning if the label of the pack does not match,
        # or if it is in fact a pack(push,n)
        my $label=$2;
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        my $pack_comment=$';
2176
        $pack_comment =~ s/^\s*//;
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
        if ($pack_comment ne "") {
          print FILEO "$pack_indent$pack_comment";
        }
        while (1) {
          my $alignment=pop @pack_stack;
          if (!defined $alignment) {
            print FILEO "$pack_indent/* winemaker:warning: No pack(push,$label) found. All the stack has been popped */\n";
            last;
          }
          if (@$alignment[1] and @$alignment[1] ne $label) {
            print FILEO "$pack_indent/* winemaker:warning: Push/pop mismatch: \"@$alignment[1]\" (@$alignment[2]) != \"$label\" */\n";
          }
          print FILEO "$pack_indent#include <poppack.h>\n";
          if (@$alignment[0]) {
            last;
          }
        }

      } elsif (/^(push\s*\))/) {
        # pragma pack(push)
        # Push the current alignment
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        if (@pack_stack > 0) {
          my $alignment=$pack_stack[$#pack_stack];
          print_pack($pack_indent,@$alignment[2],$');
          push @pack_stack, [ "push", "", @$alignment[2] ];
        } else {
          print FILEO "$pack_indent/* winemaker:warning: Using 4 as the default alignment */\n";
          print_pack($pack_indent,4,$');
          push @pack_stack, [ "push", "", 4 ];
        }

      } elsif (/^((push\s*,\s*)?(\d+)\s*\))/) {
        # pragma pack([push,]n)
        # Push new alignment n
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        print_pack($pack_indent,$3,"$'");
        push @pack_stack, [ ($2 ? "push" : ""), "", $3 ];

      } elsif (/^((\w+)\s*\))/) {
        # pragma pack(label)
        # label must in fact be a macro that resolves to an integer
        # Then behaves like 'pragma pack(n)'
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        print FILEO "$pack_indent/* winemaker:warning: Assuming $2 == 4 */\n";
        print_pack($pack_indent,4,$');
        push @pack_stack, [ "", "", 4 ];

      } elsif (/^(push\s*,\s*(\w+)\s*(,\s*(\d+)\s*)?\))/) {
        # pragma pack(push,label[,n])
        # Pushes a new label on the stack. It is possible to push the same
2228
        # label multiple times. If 'n' is omitted then the alignment is
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
        # unchanged. Otherwise it becomes 'n'.
        print FILEO "$pack_indent/* winemaker: $pack_header$1 */\n";
        my $size;
        if (defined $4) {
          $size=$4;
        } elsif (@pack_stack > 0) {
          my $alignment=$pack_stack[$#pack_stack];
          $size=@$alignment[2];
        } else {
          print FILEO "$pack_indent/* winemaker:warning: Using 4 as the default alignment */\n";
          $size=4;
        }
        print_pack($pack_indent,$size,$');
        push @pack_stack, [ "push", $2, $size ];

2244
      } else {
2245 2246 2247 2248
        # pragma pack(???               -> What's that?
        print FILEO "$pack_indent/* winemaker:warning: Unknown type of pragma pack directive */\n";
        print FILEO "$pack_indent$pack_header$_";

2249
      }
2250 2251
      $modified=1;

2252
    } elsif ($is_rc) {
2253
      if ($rc_block_depth == 0 and /^(\w+\s+(BITMAP|CURSOR|FONT|FONTDIR|ICON|MESSAGETABLE|TEXT|RTF)\s+((DISCARDABLE|FIXED|IMPURE|LOADONCALL|MOVEABLE|PRELOAD|PURE)\s+)*)([\"<]?)([^\">\r\n]+)([\">]?)/) {
2254 2255 2256 2257
	my $from_file=($5 eq "<"?"":$dirname);
	my $real_include_name=get_real_include_name($line,$6,$from_file,$project,$target);
	print FILEO "$1$5$real_include_name$7$'";
	$modified|=($real_include_name ne $6);
2258

2259 2260 2261 2262 2263
      } elsif (/^(\s*RCINCLUDE\s*)([\"<]?)([^\">\r\n]+)([\">]?)/) {
	my $from_file=($2 eq "<"?"":$dirname);
	my $real_include_name=get_real_include_name($line,$3,$from_file,$project,$target);
	print FILEO "$1$2$real_include_name$4$'";
	$modified|=($real_include_name ne $3);
2264

2265 2266 2267
      } elsif ($is_rc and !$is_mfc and $rc_block_depth == 0 and /^\s*\d+\s+TEXTINCLUDE\s*/) {
	$rc_textinclude_state=1;
	print FILEO;
2268

2269
      } elsif ($rc_textinclude_state == 3 and /^(\s*\"\#\s*include\s*\"\")afxres\.h(\"\"\\r\\n\")/) {
2270
	print FILEO "$1winresrc.h$2$'";
2271
	$modified=1;
2272

2273 2274 2275 2276
      } elsif (/^\s*BEGIN(\W.*)?$/) {
	$rc_textinclude_state|=2;
	$rc_block_depth++;
	print FILEO;
2277

2278 2279 2280 2281 2282 2283
      } elsif (/^\s*END(\W.*)?$/) {
	$rc_textinclude_state=0;
	if ($rc_block_depth>0) {
	  $rc_block_depth--;
	}
	print FILEO;
2284

2285 2286 2287
      } else {
	print FILEO;
      }
2288

2289 2290 2291 2292
    } else {
      print FILEO;
    }
  }
2293

2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
  close(FILEI);
  close(FILEO);
  if ($opt_backup == 0 or $modified == 0) {
    if (!unlink("$filename.bak")) {
      print STDERR "error: unable to delete $filename.bak:\n";
      print STDERR "       $!\n";
    }
  }
}

##
2305
# Analyzes each source file in turn to find and correct issues
2306
# that would cause it not to compile.
2307
sub fix_source()
2308 2309
{
  print "Fixing the source files...\n";
2310 2311 2312
  foreach my $project (@projects) {
    foreach my $target (@$project[$P_SETTINGS],@{@$project[$P_TARGETS]}) {
      foreach my $source (@{@$target[$T_SOURCES_C]}, @{@$target[$T_SOURCES_CXX]}, @{@$target[$T_SOURCES_RC]}, @{@$target[$T_SOURCES_MISC]}) {
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
	fix_file($source,$project,$target);
      }
    }
  }
}



#####
#
# File generation
#
#####

##
2328
# A convenience function to generate all the lists (defines,
2329
# C sources, C++ source, etc.) in the Makefile
2330
sub generate_list($$$;$)
2331 2332 2333 2334 2335
{
  my $name=$_[0];
  my $last=$_[1];
  my $list=$_[2];
  my $data=$_[3];
2336
  my $first=$name;
2337 2338

  if ($name) {
2339
    printf FILEO "%-22s=",$name;
2340
  }
2341
  if (defined $list) {
2342
    foreach my $item (@$list) {
2343 2344
      my $value;
      if (defined $data) {
2345
        $value=&$data($item);
2346
      } else {
2347 2348 2349 2350 2351
        if (defined $item) {
          $value=$item;
        } else {
          $value="";
        }
2352 2353
      }
      if ($value ne "") {
2354 2355 2356 2357 2358 2359
	if ($first) {
	  print FILEO " $value";
	  $first=0;
	} else {
	  print FILEO " \\\n\t\t\t$value";
	}
2360 2361 2362 2363
      }
    }
  }
  if ($last) {
2364
    print FILEO "\n";
2365 2366 2367 2368
  }
}

##
Francois Gouget's avatar
Francois Gouget committed
2369
# Generates a project's Makefile and all the target files
2370
sub generate_project_files($)
2371 2372 2373
{
  my $project=$_[0];
  my $project_settings=@$project[$P_SETTINGS];
2374
  my @dll_list=();
2375
  my @lib_list=();
2376
  my @exe_list=();
2377 2378

  # Then sort the targets and separate the libraries from the programs
2379
  foreach my $target (sort { @$a[$T_NAME] cmp @$b[$T_NAME] } @{@$project[$P_TARGETS]}) {
2380
    if (@$target[$T_TYPE] == $TT_DLL) {
2381
      push @dll_list,$target;
2382 2383
    } elsif (@$target[$T_TYPE] == $TT_LIB) {
      push @lib_list,$target;
2384
    } else {
2385
      push @exe_list,$target;
2386 2387 2388
    }
  }
  @$project[$P_TARGETS]=[];
2389
  push @{@$project[$P_TARGETS]}, @dll_list;
2390
  push @{@$project[$P_TARGETS]}, @lib_list;
2391
  push @{@$project[$P_TARGETS]}, @exe_list;
2392

2393 2394
  if (!open(FILEO,">@$project[$P_PATH]Makefile")) {
    print STDERR "error: could not open \"@$project[$P_PATH]/Makefile\" for writing\n";
2395 2396 2397 2398
    print STDERR "       $!\n";
    return;
  }

2399 2400 2401 2402 2403 2404 2405
  my $cpp_to_object;
  if (@$project_settings[$T_FLAGS] & $TF_HASCXX) {
    $cpp_to_object=".cxx=.o";
  } else {
    $cpp_to_object=".cpp=.o";
  }

2406
  print FILEO "### Generated by Winemaker $version\n";
2407 2408 2409 2410 2411 2412 2413
  print FILEO "###\n";
  print FILEO "### Invocation command line was\n";
  print FILEO "### $0";
  foreach(@ARGV) {
    print FILEO " $_";
  }
  print FILEO "\n\n\n";
2414

2415
  generate_list("SRCDIR",1,[ "." ]);
2416
  if (@$project[$P_PATH] eq "") {
2417
    # This is the main project. It is also responsible for recursively
2418
    # calling the other projects
2419
    generate_list("SUBDIRS",1,\@projects,sub
2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
		  {
		    if ($_[0] != \@main_project) {
		      my $subdir=@{$_[0]}[$P_PATH];
		      $subdir =~ s+/$++;
		      return $subdir;
		    }
		    # Eliminating the main project by returning undefined!
		  });
  }
  if (@{@$project[$P_TARGETS]} > 0) {
2430
    generate_list("DLLS",1,\@dll_list,sub
2431 2432 2433
		  {
		    return @{$_[0]}[$T_NAME];
		  });
2434 2435 2436 2437
    generate_list("LIBS",1,\@lib_list,sub
		  {
		    return @{$_[0]}[$T_NAME];
		  });
2438
    generate_list("EXES",1,\@exe_list,sub
2439
		  {
2440
		    return "@{$_[0]}[$T_NAME]";
2441
		  });
2442
    print FILEO "\n\n\n";
2443

2444
    print FILEO "### Common settings\n\n";
2445
    # Make it so that the project-wide settings override the global settings
2446 2447 2448
    generate_list("CEXTRA",1,@$project_settings[$T_CEXTRA]);
    generate_list("CXXEXTRA",1,@$project_settings[$T_CXXEXTRA]);
    generate_list("RCEXTRA",1,@$project_settings[$T_RCEXTRA]);
2449
    generate_list("DEFINES",1,@$project_settings[$T_DEFINES]);
2450 2451
    generate_list("INCLUDE_PATH",1,@$project_settings[$T_INCLUDE_PATH]);
    generate_list("DLL_PATH",1,@$project_settings[$T_DLL_PATH]);
2452
    generate_list("DLL_IMPORTS",1,@$project_settings[$T_DLLS]);
2453 2454
    generate_list("LIBRARY_PATH",1,@$project_settings[$T_LIBRARY_PATH]);
    generate_list("LIBRARIES",1,@$project_settings[$T_LIBRARIES]);
2455 2456 2457 2458 2459
    print FILEO "\n\n";

    my $extra_source_count=@{@$project_settings[$T_SOURCES_C]}+
                           @{@$project_settings[$T_SOURCES_CXX]}+
                           @{@$project_settings[$T_SOURCES_RC]};
2460
    my $no_extra=($extra_source_count == 0);
2461 2462 2463 2464 2465
    if (!$no_extra) {
      print FILEO "### Extra source lists\n\n";
      generate_list("EXTRA_C_SRCS",1,@$project_settings[$T_SOURCES_C]);
      generate_list("EXTRA_CXX_SRCS",1,@$project_settings[$T_SOURCES_CXX]);
      generate_list("EXTRA_RC_SRCS",1,@$project_settings[$T_SOURCES_RC]);
2466
      print FILEO "\n";
2467
      generate_list("EXTRA_OBJS",1,["\$(EXTRA_C_SRCS:.c=.o)","\$(EXTRA_CXX_SRCS:$cpp_to_object)"]);
2468
      print FILEO "\n\n\n";
2469
    }
2470

2471
    # Iterate over all the targets...
2472
    foreach my $target (@{@$project[$P_TARGETS]}) {
2473
      print FILEO "### @$target[$T_NAME] sources and settings\n\n";
2474 2475
      my $canon=canonize("@$target[$T_NAME]");
      $canon =~ s+_so$++;
2476 2477

      generate_list("${canon}_MODULE",1,[@$target[$T_NAME]]);
2478 2479 2480
      generate_list("${canon}_C_SRCS",1,@$target[$T_SOURCES_C]);
      generate_list("${canon}_CXX_SRCS",1,@$target[$T_SOURCES_CXX]);
      generate_list("${canon}_RC_SRCS",1,@$target[$T_SOURCES_RC]);
2481
      generate_list("${canon}_LDFLAGS",1,@$target[$T_LDFLAGS]);
2482
      generate_list("${canon}_ARFLAGS",1,@$target[$T_ARFLAGS]);
2483
      generate_list("${canon}_DLL_PATH",1,@$target[$T_DLL_PATH]);
2484
      generate_list("${canon}_DLLS",1,@$target[$T_DLLS]);
2485 2486
      generate_list("${canon}_LIBRARY_PATH",1,@$target[$T_LIBRARY_PATH]);
      generate_list("${canon}_LIBRARIES",1,@$target[$T_LIBRARIES]);
2487
      print FILEO "\n";
2488
      generate_list("${canon}_OBJS",1,["\$(${canon}_C_SRCS:.c=.o)","\$(${canon}_CXX_SRCS:$cpp_to_object)","\$(${canon}_RC_SRCS:.rc=.res)"]);
2489
      print FILEO "\n\n\n";
2490 2491
    }
    print FILEO "### Global source lists\n\n";
2492
    generate_list("C_SRCS",$no_extra,@$project[$P_TARGETS],sub
2493 2494 2495 2496 2497 2498 2499 2500
		  {
		    my $canon=canonize(@{$_[0]}[$T_NAME]);
		    $canon =~ s+_so$++;
		    return "\$(${canon}_C_SRCS)";
		  });
    if (!$no_extra) {
      generate_list("",1,[ "\$(EXTRA_C_SRCS)" ]);
    }
2501
    generate_list("CXX_SRCS",$no_extra,@$project[$P_TARGETS],sub
2502 2503 2504 2505 2506 2507 2508 2509
		  {
		    my $canon=canonize(@{$_[0]}[$T_NAME]);
		    $canon =~ s+_so$++;
		    return "\$(${canon}_CXX_SRCS)";
		  });
    if (!$no_extra) {
      generate_list("",1,[ "\$(EXTRA_CXX_SRCS)" ]);
    }
2510
    generate_list("RC_SRCS",$no_extra,@$project[$P_TARGETS],sub
2511 2512 2513 2514 2515 2516
		  {
		    my $canon=canonize(@{$_[0]}[$T_NAME]);
		    $canon =~ s+_so$++;
		    return "\$(${canon}_RC_SRCS)";
		  });
    if (!$no_extra) {
2517
      generate_list("",1,[ "\$(EXTRA_RC_SRCS)" ]);
2518 2519
    }
  }
2520 2521 2522 2523 2524
  print FILEO "\n\n";
  print FILEO "### Tools\n\n";
  print FILEO "CC = winegcc\n";
  print FILEO "CXX = wineg++\n";
  print FILEO "RC = wrc\n";
2525
  print FILEO "AR = ar\n";
2526
  print FILEO "\n\n";
2527

2528
  print FILEO "### Generic targets\n\n";
2529
  print FILEO "all:";
2530
  if (@$project[$P_PATH] eq "") {
2531
    print FILEO " \$(SUBDIRS)";
2532
  }
2533
  if (@{@$project[$P_TARGETS]} > 0) {
2534
    print FILEO " \$(DLLS:%=%.so) \$(LIBS) \$(EXES)";
2535 2536
  }
  print FILEO "\n\n";
2537 2538 2539 2540 2541 2542 2543 2544 2545
  print FILEO "### Build rules\n";
  print FILEO "\n";
  print FILEO ".PHONY: all clean dummy\n";
  print FILEO "\n";
  print FILEO "\$(SUBDIRS): dummy\n";
  print FILEO "\t\@cd \$\@ && \$(MAKE)\n";
  print FILEO "\n";
  print FILEO "# Implicit rules\n";
  print FILEO "\n";
2546
  print FILEO ".SUFFIXES: .cpp .cxx .rc .res\n";
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
  print FILEO "DEFINCL = \$(INCLUDE_PATH) \$(DEFINES) \$(OPTIONS)\n";
  print FILEO "\n";
  print FILEO ".c.o:\n";
  print FILEO "\t\$(CC) -c \$(CFLAGS) \$(CEXTRA) \$(DEFINCL) -o \$\@ \$<\n";
  print FILEO "\n";
  print FILEO ".cpp.o:\n";
  print FILEO "\t\$(CXX) -c \$(CXXFLAGS) \$(CXXEXTRA) \$(DEFINCL) -o \$\@ \$<\n";
  print FILEO "\n";
  print FILEO ".cxx.o:\n";
  print FILEO "\t\$(CXX) -c \$(CXXFLAGS) \$(CXXEXTRA) \$(DEFINCL) -o \$\@ \$<\n";
  print FILEO "\n";
  print FILEO ".rc.res:\n";
  print FILEO "\t\$(RC) \$(RCFLAGS) \$(RCEXTRA) \$(DEFINCL) -fo\$@ \$<\n";
  print FILEO "\n";
  print FILEO "# Rules for cleaning\n";
  print FILEO "\n";
2563
  print FILEO "CLEAN_FILES     = y.tab.c y.tab.h lex.yy.c core *.orig *.rej \\\n";
2564 2565 2566
  print FILEO "                  \\\\\\#*\\\\\\# *~ *% .\\\\\\#*\n";
  print FILEO "\n";
  print FILEO "clean:: \$(SUBDIRS:%=%/__clean__) \$(EXTRASUBDIRS:%=%/__clean__)\n";
2567
  print FILEO "\t\$(RM) \$(CLEAN_FILES) \$(RC_SRCS:.rc=.res) \$(C_SRCS:.c=.o) \$(CXX_SRCS:$cpp_to_object)\n";
2568
  print FILEO "\t\$(RM) \$(DLLS:%=%.so) \$(LIBS) \$(EXES) \$(EXES:%=%.so)\n";
2569 2570 2571 2572 2573 2574 2575
  print FILEO "\n";
  print FILEO "\$(SUBDIRS:%=%/__clean__): dummy\n";
  print FILEO "\tcd `dirname \$\@` && \$(MAKE) clean\n";
  print FILEO "\n";
  print FILEO "\$(EXTRASUBDIRS:%=%/__clean__): dummy\n";
  print FILEO "\t-cd `dirname \$\@` && \$(RM) \$(CLEAN_FILES)\n";
  print FILEO "\n";
2576

2577
  if (@{@$project[$P_TARGETS]} > 0) {
Francois Gouget's avatar
Francois Gouget committed
2578
    print FILEO "### Target specific build rules\n";
2579
    print FILEO "DEFLIB = \$(LIBRARY_PATH) \$(LIBRARIES) \$(DLL_PATH) \$(DLL_IMPORTS:%=-l%)\n\n";
2580
    foreach my $target (@{@$project[$P_TARGETS]}) {
2581 2582
      my $canon=canonize("@$target[$T_NAME]");
      $canon =~ s/_so$//;
2583

2584 2585 2586
      if (@$target[$T_TYPE] == $TT_DLL && (@$project_settings[$T_FLAGS] & $TF_HASDEF)) {
        print FILEO "\$(${canon}_MODULE).so: \$(${canon}_OBJS) \$(${canon}_MODULE:.dll=.def)\n";
      } elsif (@$target[$T_TYPE] == $TT_DLL) {
2587 2588
        print FILEO "\$(${canon}_MODULE).so: \$(${canon}_OBJS) \$(${canon}_MODULE:.dll=.spec)\n";
      } else {
2589
        print FILEO "\$(${canon}_MODULE): \$(${canon}_OBJS)\n";
2590
      }
2591 2592 2593

      if (@$target[$T_TYPE] == $TT_LIB) {
        print FILEO "\t\$(AR) \$(${canon}_ARFLAGS) \$\@ \$(${canon}_OBJS)\n";
2594
      } else {
2595 2596 2597 2598 2599 2600
        if (@{@$target[$T_SOURCES_CXX]} > 0 or @{@$project_settings[$T_SOURCES_CXX]} > 0) {
          print FILEO "\t\$(CXX)";
        } else {
          print FILEO "\t\$(CC)";
        }
        print FILEO " \$(${canon}_LDFLAGS) -o \$\@ \$(${canon}_OBJS) \$(${canon}_LIBRARY_PATH) \$(DEFLIB) \$(${canon}_DLLS:%=-l%) \$(${canon}_LIBRARIES:%=-l%)\n";
2601
      }
2602
      print FILEO "\n\n";
2603 2604 2605
    }
  }
  close(FILEO);
2606

2607 2608 2609 2610
}


##
2611
# This is where we finally generate files. In fact this method does not
2612
# do anything itself but calls the methods that do the actual work.
2613
sub generate()
2614 2615 2616
{
  print "Generating project files...\n";

2617
  foreach my $project (@projects) {
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
    my $path=@$project[$P_PATH];
    if ($path eq "") {
      $path=".";
    } else {
      $path =~ s+/$++;
    }
    print "  $path\n";
    generate_project_files($project);
  }
}



#####
#
# Option defaults
#
#####

$opt_backup=1;
$opt_lower=$OPT_LOWER_UPPERCASE;
2639
$opt_lower_include=1;
2640

2641 2642
$opt_work_dir=undef;
$opt_single_target=undef;
2643 2644
$opt_target_type=$TT_GUIEXE;
$opt_flags=0;
2645
$opt_arch=$OPT_ARCH_DEFAULT;
2646 2647 2648
$opt_is_interactive=$OPT_ASK_NO;
$opt_ask_project_options=$OPT_ASK_NO;
$opt_ask_target_options=$OPT_ASK_NO;
2649
$opt_no_generated_files=0;
2650
$opt_no_source_fix=0;
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
$opt_no_banner=0;



#####
#
# Main
#
#####

2661
sub print_banner()
2662 2663
{
  print "Winemaker $version\n";
2664
  print "Copyright 2000-2004 Francois Gouget <fgouget\@codeweavers.com> for CodeWeavers\n";
2665
  print "Copyright 2004 Dimitrie O. Paun\n";
2666
  print "Copyright 2009-2012 André Hentschel\n";
2667 2668
}

2669
sub usage()
2670 2671
{
  print_banner();
2672
  print STDERR "Usage: winemaker [--nobanner] [--backup|--nobackup] [--nosource-fix]\n";
2673
  print STDERR "                 [--lower-none|--lower-all|--lower-uppercase]\n";
2674
  print STDERR "                 [--lower-include|--nolower-include] [--mfc|--nomfc]\n";
2675
  print STDERR "                 [--guiexe|--windows|--cuiexe|--console|--dll|--lib]\n";
2676
  print STDERR "                 [-Dmacro[=defn]] [-Idir] [-Pdir] [-idll] [-Ldir] [-llibrary]\n";
2677
  print STDERR "                 [--nodlls] [--nomsvcrt] [--interactive] [--single-target name]\n";
2678
  print STDERR "                 [--generated-files|--nogenerated-files]\n";
2679
  print STDERR "                 [--wine32]\n";
2680
  print STDERR "                 work_directory|project_file|workspace_file\n";
2681
  print STDERR "\nWinemaker is designed to recursively convert all the Windows sources found in\n";
2682 2683
  print STDERR "the specified directory or project-file, so that they can be compiled with Winelib.\n";
  print STDERR "During this process it will modify and rename some of the corresponding files.\n";
2684 2685 2686 2687
  print STDERR "\tPlease read the manual page before use.\n";
  exit (2);
}

2688 2689
target_init(\@global_settings);

2690 2691
foreach(@ARGV) {
  my $arg=$_;
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
  # General options
  if ($arg eq "--nobanner") {
    $opt_no_banner=1;
  } elsif ($arg eq "--backup") {
    $opt_backup=1;
  } elsif ($arg eq "--nobackup") {
    $opt_backup=0;
  } elsif ($arg eq "--single-target") {
    $opt_single_target=shift @ARGV;
  } elsif ($arg eq "--lower-none") {
    $opt_lower=$OPT_LOWER_NONE;
  } elsif ($arg eq "--lower-all") {
    $opt_lower=$OPT_LOWER_ALL;
  } elsif ($arg eq "--lower-uppercase") {
    $opt_lower=$OPT_LOWER_UPPERCASE;
2707 2708
  } elsif ($arg eq "--lower-include") {
    $opt_lower_include=1;
2709
  } elsif ($arg eq "--nolower-include") {
2710
    $opt_lower_include=0;
2711 2712
  } elsif ($arg eq "--nosource-fix") {
    $opt_no_source_fix=1;
2713 2714
  } elsif ($arg eq "--generated-files") {
    $opt_no_generated_files=0;
2715
  } elsif ($arg eq "--nogenerated-files") {
2716
    $opt_no_generated_files=1;
2717 2718
  } elsif ($arg eq "--wine32") {
    $opt_arch=$OPT_ARCH_32;
2719 2720 2721 2722
  } elsif ($arg =~ /^-D/) {
    push @{$global_settings[$T_DEFINES]},$arg;
  } elsif ($arg =~ /^-I/) {
    push @{$global_settings[$T_INCLUDE_PATH]},$arg;
2723 2724 2725
  } elsif ($arg =~ /^-P/) {
    push @{$global_settings[$T_DLL_PATH]},"-L$'";
  } elsif ($arg =~ /^-i/) {
2726
    push @{$global_settings[$T_DLLS]},$';
2727 2728
  } elsif ($arg =~ /^-L/) {
    push @{$global_settings[$T_LIBRARY_PATH]},$arg;
2729
  } elsif ($arg =~ /^-l/) {
2730
    push @{$global_settings[$T_LIBRARIES]},$arg;
2731 2732 2733 2734

  # 'Source'-based method options
  } elsif ($arg eq "--dll") {
    $opt_target_type=$TT_DLL;
2735 2736
  } elsif ($arg eq "--lib") {
    $opt_target_type=$TT_LIB;
2737 2738 2739 2740 2741 2742 2743 2744 2745
  } elsif ($arg eq "--guiexe" or $arg eq "--windows") {
    $opt_target_type=$TT_GUIEXE;
  } elsif ($arg eq "--cuiexe" or $arg eq "--console") {
    $opt_target_type=$TT_CUIEXE;
  } elsif ($arg eq "--interactive") {
    $opt_is_interactive=$OPT_ASK_YES;
    $opt_ask_project_options=$OPT_ASK_YES;
    $opt_ask_target_options=$OPT_ASK_YES;
  } elsif ($arg eq "--mfc") {
2746
    $opt_flags|=$TF_MFC;
2747
  } elsif ($arg eq "--nomfc") {
2748 2749 2750 2751
    $opt_flags&=~$TF_MFC;
    $opt_flags|=$TF_NOMFC;
  } elsif ($arg eq "--nodlls") {
    $opt_flags|=$TF_NODLLS;
2752 2753
  } elsif ($arg eq "--nomsvcrt") {
    $opt_flags|=$TF_NOMSVCRT;
2754 2755 2756 2757

  # Catch errors
  } else {
    if ($arg ne "--help" and $arg ne "-h" and $arg ne "-?") {
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
        if (!defined $opt_work_dir and !defined $opt_work_file) {
            if (-f $arg) {
                $opt_work_file=$arg;
            }
            else {
                $opt_work_dir=$arg;
            }
        } else {
            print STDERR "error: the work directory, \"$arg\", has already been specified (was \"$opt_work_dir\")\n";
            usage();
        }
2769
    } else {
2770
        usage();
2771 2772 2773 2774
    }
  }
}

2775 2776
if (!defined $opt_work_dir and !defined $opt_work_file) {
  print STDERR "error: you must specify the directory or project file containing the sources to be converted\n";
2777
  usage();
2778
} elsif (defined $opt_work_dir and !chdir $opt_work_dir) {
2779 2780
  print STDERR "error: could not chdir to the work directory\n";
  print STDERR "       $!\n";
2781
  usage();
2782 2783
}

2784 2785
if ($opt_no_banner == 0) {
  print_banner();
2786 2787
}

2788
project_init(\@main_project, "", \@global_settings);
2789

2790 2791 2792 2793 2794 2795 2796
# Fix the file and directory names
fix_file_and_directory_names(".");

# Scan the sources to identify the projects and targets
source_scan();

# Fix the source files
2797 2798 2799
if (! $opt_no_source_fix) {
  fix_source();
}
2800 2801

# Generate the Makefile and the spec file
2802
if (! $opt_no_generated_files) {
2803 2804
  generate();
}